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

1.导入mysql-connection的jar包,在idea内创建一个lib文件夹将该文件放入

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

2.点击这个或者(ctrl+alt+shift+s)然后选择modules内选择jar包

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

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

3. 然后在src内创建class文件输入以下代码

package com;

import java.sql.*;

public class Test {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            //1.加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获得链接
            String userName = "root";//MySQL默认用户名
            String passWord = "aa5153222";//MySQL密码
            String url = "jdbc:mysql://localhost:3306/hwk1?serverTimezone=UTC";//hwk1为数据库名称
            connection = DriverManager.getConnection(url, userName, passWord);
            //3.定义sql,创建状态通道(进行sql语句的发送)
            statement = connection.createStatement();
            resultSet = statement.executeQuery("select * from employee"); //executeQuery(sql) 执行查询,employee是表名
            //4.取出结果采集信息
            while(resultSet.next()){
                System.out.println("员工ID:"+resultSet.getString("empid")+",姓名:"+resultSet.getString("name")+",性别:"+resultSet.getString("sex"));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            try {
                //5.关闭资源
                if (resultSet != null) {
                    resultSet.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
上一篇:java每日一题(11)


下一篇:SQL注入命令优化