package com.zhuke.app;
import java.sql.*;
public class AddDepartment {
/*jdbc:mysql://服务器地址:端口/数据库名*/
static final String URL = "jdbc:mysql://localhost:3306/stu";
static final String driver = "com.mysql.cj.jdbc.Driver";
static final String USERNAME = "root";
static final String PASSWORD = "123456";
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//加载JDBC驱动程序
Class.forName(driver);
//创建数据库连接
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
//创建操作命令
stmt = conn.createStatement();
//执行SQL,获取到返回结果
String sql;
sql = "SELECT id, name FROM stu";
rs = stmt.executeQuery(sql);
//处理结果集
while (rs.next()) {
// 通过字段检索
String id = rs.getString("id");
String name = rs.getString("name");
// 输出数据
System.out.print("ID: " + id);
System.out.print(", 姓名: " + name);
System.out.print("\n");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 释放资源,要按这个顺序
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
JAVA连接数据库(使用Navicat)
于 2021-11-23 21:44:49 首次发布