jdbc建立java和sql的连接

jdbc建立java和sql的连接

一.导包

1.首先新建一个项目

2.再新建一个包lib

3.把下好的sql包粘贴到lib里

4.右键lib包点击add as library

结束

二.注册驱动:
java 复制代码
DriverManager.registerDriver(new Driver());
三.建立与数据库的连接:
java 复制代码
 String url="jdbc:mysql://127.0.0.1:sql端口号/schooldb?serverTimezone=Asia/Shanghai";
        String user="root"; //账户
        String password="root"; //密码
        Connection connection=DriverManager.getConnection(url,user,password);
四.发送sql
java 复制代码
 Statement statement=connection.createStatement();
 statement.executeUpdate("insert into major(name)value('数学')");
五.关闭与数据库的连接:
java 复制代码
statement.close();
connection.close();

插入方法eg:

java 复制代码
public static void main(String[] args) throws SQLException {
        SqlOperate.insert("lzy","男","1979-4-21","13152113467",1.88);
    }
    public static void insert(String name,String gender, String birthday,String phone,double height) throws SQLException {
        //注册驱动
        DriverManager.registerDriver(new Driver());
        String url="jdbc:mysql://127.0.0.1:3306/schooldb?serverTimezone=Asia/Shanghai";
        String user="root";
        String password="root";
        //建立与数据库的连接
        Connection connection=DriverManager.getConnection(url,user,password);
        //发送sql
        Statement statement=connection.createStatement();
        statement.executeUpdate("update student set name='"+name+"',gender='"+gender+"',birthday='"+birthday+"',phone='"+phone+"',height="+height+"");
        //关闭与数据库的连接
        statement.close();
        connection.close();
    }
PreparedStatement实现发送sql
java 复制代码
PreparedStatement ps=connection.prepareStatement("insert into major(name)value(?)");    //?是占位符,表示要插入一个参数
        ps.setObject(1,"智能");   //1表示在第一个?位置插入数据
        ps.executeUpdate();
java 复制代码
PreparedStatement ps=connection.prepareStatement("update student set name=?,gender=?,birthday=?,phone=?,height=? where number=?");
        ps.setObject(1,name);
        ps.setObject(2,gender);
        ps.setObject(3,birthday);
        ps.setObject(4,phone);
        ps.setObject(5,height);
        ps.setObject(6,number);
        ps.executeUpdate();
PreparedStatement和Statement本质区别:PS的?占位符可以在参数进来时进行验证,防止sql注入攻击,更安全
相关推荐
小陳参上3 小时前
用Python创建一个Discord聊天机器人
jvm·数据库·python
曹牧4 小时前
BeanUtils.copyProperties‌
java
changhong19864 小时前
如何在 Spring Boot 中配置数据库?
数据库·spring boot·后端
QWQ___qwq4 小时前
Java线程安全深度总结:基本类型与引用类型的本质区别
java·安全·面试
识君啊5 小时前
Java异常处理:中小厂面试通关指南
java·开发语言·面试·异常处理·exception·中小厂
月月玩代码7 小时前
Actuator,Spring Boot应用监控与管理端点!
java·spring boot·后端
执笔画情ora7 小时前
Postgresql数据库管理-pg_xact
数据库·postgresql·oracle
南棱笑笑生7 小时前
20260310在瑞芯微原厂RK3576的Android14查看系统休眠时间
服务器·网络·数据库·rockchip
阿珍爱上了阿强,在一个有星星的夜晚8 小时前
node后端页面性能监测分析
java·学习方法
XDHCOM8 小时前
ORA-32152报错咋整啊,数据库操作遇到null number问题远程帮忙修复
服务器·数据库·oracle