下面是我连接数据库的代码:
import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.ResultSet; 4 import java.sql.SQLException; 5 6 public class Database { 7 private static String url = "jdbc:mysql://localhost:3306/tally_book?useUnicode=true&characterEncoding=utf8"; 8 private static String user = "root"; 9 private static String password = "ym123"; 10 private static String jdbcName="com.mysql.jdbc.Driver"; 11 private Connection con=null; 12 public static Connection getConnection() { 13 Connection con=null; 14 try { 15 Class.forName(jdbcName); 16 con=DriverManager.getConnection(url, user, password); 17 System.out.println("数据库连接成功"); 18 } catch (Exception e) { 19 // TODO Auto-generated catch block 20 System.out.println("数据库连接失败"); 21 e.printStackTrace(); 22 } 23 return con; 24 } 25 26 public static void close(Connection con) { 27 if(con!=null) { 28 try { 29 con.close(); 30 }catch(SQLException e) { 31 e.printStackTrace(); 32 } 33 } 34 } 35 36 public static void close(java.sql.Statement st,Connection conn) { 37 if(st!=null) { 38 try { 39 st.close(); 40 }catch(SQLException e) { 41 e.printStackTrace(); 42 } 43 } 44 if(conn!=null) { 45 try { 46 conn.close(); 47 }catch(SQLException e) { 48 e.printStackTrace(); 49 } 50 } 51 } 52 53 public static void close(ResultSet rs, java.sql.Statement st, Connection conn) { 54 if(rs!=null) { 55 try { 56 rs.close(); 57 } catch (SQLException e) { 58 e.printStackTrace(); 59 } 60 } 61 if(st!=null) { 62 try { 63 st.close(); 64 } catch (SQLException e) { 65 e.printStackTrace(); 66 } 67 } 68 if(conn!=null) { 69 try { 70 conn.close(); 71 } catch (SQLException e) { 72 e.printStackTrace(); 73 } 74 } 75 } 76 77 public static void main(String[] args) throws SQLException { 78 Connection conn = getConnection(); 79 }