jdbc
import java.sql.*;
public class JDBC_base {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
try {
// 1. 注册驱动
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
// System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver"); // 告诉 jdbc 驱动存在
// Class.forName("com.mysql.jdbc.Driver"); // 根据这个类的名字装载到虚拟机里
// 2. 建立连接, 根据这个 url 与 驱动建立连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=UTF-8&useSSL=false", "root", "000000fzx");
// 3. 创建语句
Statement st = connection.createStatement();
// 4. 执行语句
ResultSet rSet = st.executeQuery("select id, score, name from user");
// 5. 处理结果
while(rSet.next()) {
// System.out.println(rSet.getObject(1) + "\t" + rSet.getObject(2) + "\t");
int id = rSet.getInt("id");
String name = rSet.getString("name");
float score = rSet.getFloat("score");
System.out.print("ID: " + id);
System.out.print(", 名字: " + name);
System.out.println(", 分数: " + score);
}
// 6. 释放资源
rSet.close();
st.close();
connection.close();
}catch (SQLException se) {
se.printStackTrace();
}
}
运行结果:
ID: 1, 名字: fzx, 分数: 10.0
ID: 2, 名字: yym, 分数: 12.0
ID: 3, 名字: fzx, 分数: 10.0
ID: 4, 名字: yym, 分数: 12.0