20201103王永苗

数据库加载驱动,创建连接,执行sql语句,关闭资源


package com.itlaobing.dbhelper;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class DBHelper {
    /*用main测试*/
    public static void main(String[] args) {
        try {
            save();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*定义添加用户的方法*/
    public static void save() throws Exception {
        //1、加载数据库驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2、创建数据库连接
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_user","root","");
        //3、拼写sql语句
        String sql = "INSERT INTO t_user (userName,`passWord`,gender)VALUES('宫本武藏','rb123','女')";
        //4、发送sql
        PreparedStatement prepareStatement = connection.prepareStatement(sql);
        //5、执行sql
        int i = prepareStatement.executeUpdate();
        //6、处理结果
        if(i > 0) {
            System.out.println("添加成功");
        }
        //7、关闭资源
        prepareStatement.close();
        connection.close();
    }
}


标签

评论

© 2021 成都云创动力科技有限公司 蜀ICP备20006351号-1