1. 安装JDBC
- 官网地址:官网地址
- 选择
- 下载后,解压缩,然后将mysql-connector-j-9.0.0.jar文件放到项目目录下
编写操作数据库代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class HelloWorld {
public static void main(String[] args) {
Connection conn = null;
Statement state = null;
ResultSet ret = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname", "username", "password");
state = conn.createStatement();
String query = "select * from tablename";
ret = state.executeQuery(query);
while (ret.next()) {
String columnValue = ret.getString("columnname");
System.out.println(columnValue);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ret != null) ret.close();
if (state != null) state.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
编译运行
javac -encoding utf-8 .\HelloWorld.java
java -cp ".;mysql-connector-j-9.0.0.jar" HelloWorld