package com.test3;
import java.sql.*;
import java.util.List;
//main函数测试类
public class text_01 {
private static String url="jdbc:mysql://localhost:3306/dbc?characterEncoding=utf-8";
private static String root ="root";
private static String password = "123456 ";
private static String driver ="com.mysql.cj.jdbc.Driver";
public static void main(String[] args)throws ClassNotFoundException , SQLException {
try{
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,root,password);
String sql = "select *from user ";
Statement stmt =conn.createStatement();
//执行语句
ResultSet rs = stmt.executeQuery(sql);
//实例化list对象
while(rs.next()){
int a = rs.getInt("id");
String b= rs.getString("username"); //获取数据
String c = rs.getString("password");
System.out.println(a +"username "+ b +" password " +c);
}
}catch(ClassNotFoundException e ){
System.out.println("驱动加载异常。。。");
e.printStackTrace();
}
}
}
JDBC工具类
package Complete;
import java.io.IOException;
import java.sql.*;
public class JDBCUtils {
private static String url= "jdbc:mysql://localhost:3306/dbc?characterEncoding =utf-8";
private static String root="root";
private static String pass = "123456";
private static String driver = "com.mysql.cj.jdbc.Driver"; //高版本的用这个
static{
try{
Class.forName(driver);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
public static Connection getConnection()throws SQLException {
return DriverManager.getConnection(url,root,pass);
}
public void close(PreparedStatement prepared,Connection conn){
try{
if(prepared != null){
prepared.close();
}
}catch(SQLException e){
e.printStackTrace();
}
try{
if(conn != null){
conn.close();
}
}catch(SQLException e){
e.printStackTrace();
}
}
public static void close(ResultSet rs, PreparedStatement prepared, Connection conn){
try{
if(conn != null){
conn.close();
}
}catch(SQLException e){
e.printStackTrace();
}
try{
if(prepared != null){
prepared.close();
}
}catch(SQLException e){
e.printStackTrace();
}
try{
if(conn != null){
conn.close();
}
}catch(SQLException e){
e.printStackTrace();
}
}
}