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 @   STDU_DREAM  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示