JDBC

JDBC:java连接数据库

固定步骤

加载驱动
连接数据库
向数据库发送SQL的对象Statement:CRUD
编写SQL(根据业务编写不同的SQL语句)
执行SQL
关闭连接
注:在数据库的编写之中尽量的采用prepareStatement

package com.li.Dao;


import java.sql.*;

public class Daodemo0 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String url = "jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false";
String root="root";
String password="lyj18366635303";
String driver = "com.mysql.cj.jdbc.Driver";
Class.forName(driver);
Connection connection = DriverManager.getConnection(url,root,password);
// String sql="select * from class";
String sql="insert into class (categoryId,pId,categoryName) values(?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,12);
preparedStatement.setInt(2,12);
preparedStatement.setString(3,"web");
int i = preparedStatement.executeUpdate();

if (i>0){
System.out.println("插入成功");
}
preparedStatement.close();
connection.close();

}
}



注:在使用statement与PrepareSatatement的区别

Statement
int i = preparedStatement.executeUpdate(sql);
prepareStatement
int i = preparedStatement.executeUpdate();

posted @ 2023-03-07 22:37  STDU_DREAM  阅读(11)  评论(0编辑  收藏  举报