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基本编程的步骤:
加载驱动
其使用的方法有Class.forName()或者
Class.forName().newInstance()或者
new DriverName() 连接
数据库
DriverManager.getConnection() 执行SQL语句
Connection.CreateStatement()
Statement.executeQuery()
Statement.executeUpdate() 取得结果集
while(rs.next()) 显示数据
将数据库中的各种类型转化为java中的类型(getXXX)方法 关闭
close the resultset
close the statement
close the connection
实例:
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();