Prerequisites:
Step 1:Down load Mysql database(http://dev.mysql.com/downloads/)
Step2:Down load Mysql-connector-java JAR(http://downloads.mysql.com/archives.php?p=mysql-connector-java-5.0&o=other)
Step2:Down load Mysql-connector-java JAR(http://downloads.mysql.com/archives.php?p=mysql-connector-java-5.0&o=other)
Step4:In eclipse create new project and under your project
attach Mysql-connector-java JAR files
Code follows:
import java.sql.*;
public static void main(String[] args) throws SQLException {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/"; (Mysql server runs by default
in this port -3306)
String dbName = "test";
String driver = "com.mysql.jdbc.Driver";
String userName = "root"; (Default user Name in Mysql)
String password = "sudhakar"; (Give the same pass word while
you create database in Mysql)
try{
Class.forName(driver).newInstance();// create object of
Driver
conn = DriverManager.getConnection(url+dbName,userName,password);
// connection will be established
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from
users");
while(rs.next()){
System.out.println(rs.getString(1) + "-- "+rs.getString(2)+" -- "+rs.getString(3));
}
System.out.println("*********************************");
// *****************PREPARED
STATEMENT**************
PreparedStatement pstmt =
conn.prepareStatement("select
* from users where name = ? and sex
=?");
pstmt.setString(1, "vagdevi");
pstmt.setString(2, "F");
ResultSet rs1 = pstmt.executeQuery();
while(rs1.next())
System.out.println(rs1.getString(1) + "-- "+rs1.getString(2)+" -- "+rs1.getString(3));
System.out.println(rs1.getString(1) + "-- "+rs1.getString(2)+" -- "+rs1.getString(3));
}
//
********************Add row Insert************************
pstmt
= conn.prepareStatement("insert
into users values (?,?,?)");
pstmt.setString(1,
"Jeniffer");
pstmt.setString(2, "US");
pstmt.setString(3, "F");
int i=pstmt.executeUpdate();
if(i==1){
System.out.println("inserted the
record");
}
}catch(Exception e){
e.printStackTrace();
}finally{
conn.close();
}
}
No comments:
Post a Comment