当前位置:Gxlcms > 数据库问题 > JDBC中连接MySQL数据库

JDBC中连接MySQL数据库

时间:2021-07-01 10:21:17 帮助过:7人阅读

package qddx.JDBC; 2 import java.sql.*; 3 4 public class JDBC_Connection { 5 static String driverName = "com.mysql.jdbc.Driver";//驱动名 6 static String url="jdbc:mysql://localhost/bbs";//地址 7 static String userName="root";//账号 8 static String passWord = "674768166ws";//密码 9 static { 10 try{//连接驱动 11 Class.forName(driverName); 12 }catch(ClassNotFoundException e){ 13 e.printStackTrace(); 14 } 15 } 16 //连接数据库 17 public static Connection getConnection(){ 18 Connection conn = null; 19 try{ 20 conn = (Connection)DriverManager.getConnection(url,userName,passWord); 21 System.out.println("数据库连接成功"); 22 conn.setAutoCommit(false);// 设置事务不自动提交 23 }catch(SQLException e){ 24 e.printStackTrace(); 25 } 26 System.out.println("已经连接"); 27 return conn; 28 } 29 //关闭数据库 30 public static void free(ResultSet rs,Connection conn,Statement stmt){ 31 try{ 32 if(rs!=null){ 33 rs.close(); 34 rs=null; 35 } 36 }catch(SQLException e){ 37 e.printStackTrace(); 38 }finally{ 39 try{ 40 if(conn!=null){ 41 conn.close(); 42 conn = null; 43 } 44 if(stmt !=null){ 45 stmt.close(); 46 stmt=null; 47 } 48 }catch(SQLException e){ 49 e.printStackTrace(); 50 } 51 } 52 } 53 public static void main(String[] args) { 54 JDBC_Connection.getConnection();//启动 55 } 56 57 }

 

JDBC中连接MySQL数据库

标签:

人气教程排行