我们通过Java代码可以对各种数据库进行操作
但Java中没有内置类可以对数据库直接进行访问
这就需要我们导入第三方jar包
下载地址:http://mvnrepository.com/artifact/mysql/mysql-connector-java/8.0.11
下载成功后,我们还需要将它导入
导入JDBC的jar包
在IDEA工程下新建一个lib文件夹
将刚下载好的文件夹中的mysql-connector-java-8.0.24.jar复制粘贴到lib文件夹下
然后右键文件夹,将这个文件夹添加为库,导入完成
在编写代码操作数据库之前,我们还需要数据库.你不可能没有数据库就去操作吧
创建数据库
编写Java代码
package com.zhang.code;
import java.sql.*;
public class JDBCTest {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8","root","123456");
String sql = "select * from test01 where id > ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,1);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
Integer id = resultSet.getInt("id");
String name = resultSet.getString("name");
Float salary = resultSet.getFloat("salary");
System.out.println(id + "--->" + name + "--->" + salary);
}
} catch (Exception e){
e.printStackTrace();
} finally {
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(preparedStatement != null){
try {
preparedStatement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
点击运行,即可看到结果