MySQL database connection JDBC bitsCN.com
1 package com. frankstyle; 2 3 import java. SQL. connection; 4 import java. SQL. driverManager; 5 import java. SQL. resultSet; 6 import java. SQL. SQLException; 7 import java. SQL. statement; 8 9/** 10 * @ author wang520123fan11 * 12 */13 public class JDBC_Connection14 {15 static String driverName = "com. mysql. jdbc. driver "; 16 static String url =" jdbc: mysql: // localhost: 3306/library "; // you need to set your own database name 17 static String us Ername = "root"; 18 static String password = "520123"; 19 20 static21 {22 try {23 Class. forName (driverName); // create the driver 24 System by path. out. println ("created successfully"); 25} catch (ClassNotFoundException e) 26 {27 e. printStackTrace (); 28} 29} 30 31/** 32 * @ return Connection 33 */34 public static Connection getConnection () 35 {36 Connection conn = null; 37 try {38 conn = (Connection) DriverManager. getConnection (url, username, password); 39 Sys Tem. out. println ("database connected successfully"); 40} catch (SQLException e) 41 {42 e. printStackTrace (); 43} 44 return conn; 45} 46 47/** 48 * @ param conn Connection49 * @ param stmt Statement50 * @ param rs the ResultSet51 */52 public void close (Connection conn, statement stmt, ResultSet rs) // disconnect from inside to outside 53 {54 try {55 if (rs! = Null) 56 rs. close (); 57} catch (SQLException e) 58 {59 e. printStackTrace (); 60 System. out. println ("failed to disable ResultSet! "); 61} finally62 {63 rs = null; 64 try {65 if (stmt! = Null) 66 stmt. close (); 67} catch (SQLException e) 68 {69 e. printStackTrace (); 70 System. out. println ("disabling Statement failed! "); 71} finally72 {73 stmt = null; 74 try {75 if (conn! = Null) 76 conn. close (); 77} catch (SQLException e) 78 {79 e. printStackTrace (); 80 System. out. println ("failed to close Connection! "); 81} finally82 {83 conn = null; 84} 85} 86} 87 88} 89}
BitsCN.com