jdbc 01: 连接mysql,并实现数据插入

2年前 (2022) 程序员胖胖胖虎阿
216 0 0

jdbc连接mysql,并实现数据插入

package com.examples.jdbc.o1_连接与插入;

import java.sql.*;

/*
 jdbc数据库连接六步
 */
public class Test {

    public static void main(String[] args) {

        //为了finally语句块可以关闭连接资源
        Connection connection = null;
        Statement statement = null;

        try {

            //1. 注册驱动(前提要导入mysql的jar包)
            Driver driver = new com.mysql.jdbc.Driver();
            DriverManager.registerDriver(driver);

            //2. 获取数据库连接对象
            String url = "jdbc:mysql://ip地址:3306/数据库名";
            String userName = "XXXX";
            String passWord = "XXXX";
            connection = DriverManager.getConnection(url, userName, passWord);


            //3. 获取数据库操作对象
            statement = connection.createStatement();

            //4. 执行sql语句
            String sql = "insert into student(sname, sage) values('万城', 19)";
            int num = statement.executeUpdate(sql);
            System.out.println(num == 1 ? "插入成功" : "插入失败");

            //5. 查询结果集

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //6. 关闭资源
            if (statement != null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
版权声明:程序员胖胖胖虎阿 发表于 2022年10月29日 下午2:40。
转载请注明:jdbc 01: 连接mysql,并实现数据插入 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...