一、准备工作
1.下载并安装MySQL以及MySQL的基本操作
2.下载并安装Connector/J
二、JDBC编程步骤
代码示例:
import java.sql.*;
public class TestJDBC {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//1.Load the Driver,自动实例化,自动向DriverManager注册,不需显示调用DriverManager.registerDriver()方法
Class.forName("com.mysql.jdbc.Driver");
//2.Connect to the DataBase
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc", "root", "1234567");
//3.Execute the SQL
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from student");
while (rs.next()) { //4.Retrieve the result data
//5.将数据库中的各种类型转换为Java中的类型(getXXX)方法
System.out.println(rs.getString("name"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try { //6.Close
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
说明:
在MySQL中建立了一个名为“testjdbc"的Database,然后在testjdbc中建立一个名为”student“的table,MySQL中root的密码为”1234567“。