JDBC(Java DataBase Connectivity)由Java编写的类和接口组成,可以为多种关系数据库提供统一的访问方式,从而实现用Java代码操作数据库
开发JDBC程序,四个基本步骤
1.导入驱动包,加载驱动类
2.与数据库建立连接
Connection connection = DriverManager.getConnection(" url "," 数据库用户名","数据库密码",);
3.执行SQL语句,并返回结果
(1) Statement对象
Statement stmt = connection.createStatement();
增、删、改:
int count = stmt.executeUpdate("要执行的增、删、改sql语句");
查:
ResultSet rs = stmt.executeQuery("查询的Sql语句");
(2)PreparedStatement对象
PreparedStatement pstmt = connection.prepareStatement("要执行的增、删、查、改的sql语句") ;
增、删、改:
int count = pstmt.executeUpdate();
查:
ResultSet rs = pstmt.executeQuery();
4.处理返回结果集
如果是查询操作,可以通过循环取出结果集中的所有数据:首先通过 rs.next() 获取每行的数据,再通过 rs.getXxx() 获得行内的每列数据
while( rs.next() ) {
int stuId = rs.getlnt( " stuld ");
String stuNum = rs.getString( " stuNum " );
.........
}
JDBC访问 MySQL数据库实例
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLCon {
String url = "jdbc:mysql://localhost:3306/mo_?";
String username = "root";
String password = null;
private static Connection conn = null;
public SQLCon() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,username,password);
}
//获得连接对象
public static Connection getConnection(){
return conn;
}
//关闭连接
public static void CloseCon() throws SQLException{
conn.close();
}
}