1 package org.db; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.SQLException; 6 7 public class DBConn { 8 9 // public final static String URL = "jdbc:mysql://localhost:3306/test?useSSL=false"; 10 public final static String URL = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8"; //可以指定jdbc编码方式 11 public final static String USERNAME = "root"; 12 public final static String PASSWORD = "000000"; 13 public final static String DRIVER = "com.mysql.jdbc.Driver"; 14 15 public static Connection conn; 16 public static Connection getConn(){ 17 try { 18 Class.forName(DRIVER); 19 conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); 20 if (conn!=null) { 21 System.out.println("连接成功"); 22 } 23 return conn; 24 } catch (Exception e) { 25 e.printStackTrace(); 26 System.out.println("连接失败"); 27 return null; 28 } 29 } 30 public static void closeConn(){ 31 try { 32 if(conn!=null){ 33 conn.close(); 34 } 35 } catch (SQLException e) { 36 e.printStackTrace(); 37 } 38 } 39 }
1 package org.test; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 8 import org.db.DBConn; 9 import org.model.Login; 10 11 public class test { 12 13 public static void main(String[] args) { 14 Connection conn = DBConn.getConn(); 15 if (conn!=null) { 16 System.out.println("连接成功"); 17 try { 18 conn = DBConn.getConn(); 19 String sql = "select id,name,password,role from mbook where name=? and password=?"; 20 PreparedStatement ps = conn.prepareStatement(sql); 21 ps.setString(1,"张三"); 22 ps.setString(2,"000000"); 23 ResultSet rs = ps.executeQuery(); 24 25 while (rs.next()) { 26 Login login = new Login(); 27 login.setId(rs.getInt(1)); 28 login.setName(rs.getString(2)); 29 login.setPassword(rs.getString(3)); 30 login.setRole(rs.getBoolean(4)); 31 System.out.println("得到数据:"+login); 32 } 33 } catch (SQLException e) { 34 e.printStackTrace(); 35 }finally{ 36 DBConn.closeConn(); 37 } 38 } 39 } 40 }
时间: 2024-10-12 13:33:56