1 下載安裝Connector/J,下載地址:http://www.mysql.com/products/connector/。Connector/J是專門針對MySQL而開發的JDBC驅動程序包。
2 將安裝目錄下的mysql-connector-java-5.1.36-bin.jar添加到環境變量的classpath,或者添加到項目的Java Build Path。
3 JDBC基本編程的步驟:
實例:
package ms;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class TestMySQL {
public static void main(String[] args){
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
try{
Class.forName("com.mysql.jdbc.Driver"); //創建該字符串標識的類的實例
String url = "jdbc:mysql://localhost:3306/test"; //標識一個被注冊的驅動程序
String user = "root";
String pwd = "";
conn = DriverManager.getConnection(url, user, pwd);
stmt = conn.createStatement();
String query = "select * from person where age > 18";
rs = stmt.executeQuery(query);
while (rs.next()){
String id = rs.getString("id");
String name = rs.getString(2);
int age = rs.getInt("age");
System.out.println(id + "\t" + name + "\t" + age);
}
}
catch (ClassNotFoundException e){
e.printStackTrace();
}
catch (SQLException e){
e.printStackTrace();
}
finally {
try{
if (rs != null){
rs.close();
}
if (stmt != null){
stmt.close();
}
if (conn != null){
conn.close();
}
}
catch (SQLException e){
e.printStackTrace();
}
}
}
}
PreparedStatement的預處理語句:
String sql = "insert into person values(?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "005");
pstmt.setString(2, "Zhao");
pstmt.setInt(3, 18);
pstmt.executeUpdate();
statement語句的批處理:
Statement stmt = conn.createStatement();
stmt.addBatch("insert into person values('006', 'Zeng', 26)");
stmt.addBatch("insert into person values('007', 'Liu', 24)");
stmt.addBatch("insert into person values('008', 'Zeng', 17)");
stmt.executeBatch();
PreparedStatement語句的批處理
String sql = "insert into person values(?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "006");
pstmt.setString(2, "Zeng");
pstmt.setInt(3, 26);
pstmt.setString(1, "007");
pstmt.setString(2, "Liu");
pstmt.setInt(3, 24);
pstmt.setString(1, "008");
pstmt.setString(2, "Zeng");
pstmt.setInt(3, 17);
pstmt.executeUpdate();