方法一:
package jbdc;
import java.sql.*;
public class _1_JdbcDemo {
public static void main(String[] args) {
Connection conn = null;
Statement smt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("加载成功");
} catch (ClassNotFoundException e) {
System.out.println("加载失败");
e.printStackTrace();
}
String url = "jdbc:mysql://localhost:3306/market";
String username = "root";
String pwd = "root12345";
try {
conn = DriverManager.getConnection(url,username,pwd);
System.out.println("连接成功");
} catch (SQLException e) {
System.out.println("连接失败");
e.printStackTrace();
}
try {
smt = conn.createStatement();
String sql = "select * from user";
rs = smt.executeQuery(sql);
while(rs.next()) {
String id = rs.getString("id");
String password= rs.getString("pwd");
String name = rs.getString("xm");
String role = rs.getString("role");
System.out.println(id+" "+password+" "+name+" "+role);
}
}catch(SQLException e) {
e.printStackTrace();
}finally {
if(rs!=null)
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(smt!=null)
try {
smt.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
方法二:
package jbdc;
import java.sql.*;
public class _2_JdbcDemo2 {
public static void main(String[] args) throws SQLException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/market";
String username = "root";
String password = "root12345";
conn = DriverManager.getConnection(url,username,password);
stmt = conn.createStatement();
String sql = "select * from user";
rs = stmt.executeQuery(sql);
System.out.println("id | pwd | xm | role ");
while(rs.next()) {
int id = rs.getInt("id");
String pwd = rs.getString("pwd");
String xm = rs.getString("xm");
String role = rs.getString("role");
System.out.println(id+" | "+pwd+" | "+xm+" | "+role);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(rs!=null) rs.close();
if(conn!=null) conn.close();
if(stmt!=null) stmt.close();
}
}
}