欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JDBC(连接数据库的基本操作步骤)

程序员文章站 2024-03-17 18:23:58
...

JDBC(连接数据库的基本操作步骤)

  • 熟悉基本的数据库连接操作顺序

具体步骤见注释



import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCDemo1 {
    public static void main(String[] args) {
        String sql = null;
        Connection connection = null;
        Statement statement = null;
        try {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root", "root");
            //获取执行sql的对象
            statement = connection.createStatement();
            //为sql赋值
            sql = "INSERT INTO JOB VALUES(NULL,'LIWEICHENG','WAN') ";
            //执行sql
            int count = statement.executeUpdate(sql);
            //处理结果
            System.out.println(count);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            //释放资源
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}