首先需要引入包需要包含包含数据库编程所需的JDBC类的包。大多数情况下,使用import java.sql.*就足够 了。
然后在Java的 代码步骤上:
//com包
package com;
//如上言所述
import java.sql.*;
public class Demo1 {
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"; //用户名
String passWord = "********"; //密码
String url = "jdbc:mysql://localhost:3306/mysqlgaoji?serverTimezone=UTC";
connection = DriverManager.getConnection(url, userName, passWord);
//3. 定义sql,创建状态通道(进行sql语句的发送)
statement = connection.createStatement();
resultSet = statement.executeQuery("select * from employee");//executeAuery(sql)执行查询
//4. 取出结果集信息
while(resultSet.next()){ //判断是否有下一条数据
// 取出数剧:resultSet.getXXX("列名"); XXX表示数据类型
System.out.println("姓名:"+resultSet.getString("name"));
}
} 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();
}
}
}
}
对上面的一部分代码再次批注:
- 驱动加载:
Class.forName("com.mysql.cj.jdbc.Driver");
java1.8版本需要cj.如果在1.8之前只需要com.mysql.jdbc.Driver即可。 - 关于url地址:
String url = "jdbc:mysql://localhost:3306/mysqlgaoji?serverTimezone=UTC";
localhost是需要根据自身进行修改的 ip地址(可以这样理解)3306端口号,mysqlgaoji是数据库名称。 - 一定需要进行第五步关闭。