a、导入驱动包,加载具体驱动类Class.forName(“具体驱动类”)
b、与数据库建立连接:connection = DriverManage.getConnection(URL,UNAME,UPWD)
C、通过connection,获取到操作数据库的对象。例如:prstmt = conn.prepareStatement(sql);
(查询)处理结果集rs=pstmt.executeQuary();
完整步骤:`public static final String DBDRIVER = “com.mysql.cj.jdbc.Driver”;
public static final String DBURl = "jdbc:mysql://localhost:3306/Student?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai";
public static final String DBUSER = "root";
public static final String DBPASS = "qwert123";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement prstmt = null;
ResultSet rs = null;
try {
//导入驱动程序
Class.forName(DBDRIVER);
//与数据库建立连接
conn=DriverManager.getConnection(DBURl,DBUSER,DBPASS);
//编写sql语句(增删改查)
//增
String sql = "insert into student values(1020,'zhangsan','women','class8',95,null)";
//删
String delsql="delete from student where id =1021";
//改
String updsql="update student set name='wangqi' where id =1009 ";
//查
String selsql="SELECT * FROM student WHERE name like ?";
//执行sql
prstmt = conn.prepareStatement(selsql);//预编译
prstmt.setString(1, "%ang%");
rs = prstmt.executeQuery(); //这边括号中可不写sql
最后关闭的流程:
try {
if(rs!=null)
rs.close();
if(prstmt!=null)
prstmt.close();
if (conn!=null)
conn.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}