java連接mysql數(shù)據(jù)庫及測試是否連接成功的方法
本文實例講述了java連接mysql數(shù)據(jù)庫及測試是否連接成功的方法。分享給大家供大家參考,具體如下:
package com.test.tool;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtlTool {
public static Connection getConnection(){
String driver="com.mysql.jdbc.Driver"; //獲取mysql數(shù)據(jù)庫的驅(qū)動類
String url="jdbc:mysql://localhost:3306/test"; //連接數(shù)據(jù)庫(kucun是數(shù)據(jù)庫名)
String name="root";//連接mysql的用戶名
String pwd="123456";//連接mysql的密碼
try{
Class.forName(driver);
Connection conn=DriverManager.getConnection(url,name,pwd);//獲取連接對象
return conn;
}catch(ClassNotFoundException e){
e.printStackTrace();
return null;
}catch(SQLException e){
e.printStackTrace();
return null;
}
}
public static void closeAll(Connection conn,PreparedStatement ps,ResultSet rs){
try{
if(rs!=null){
rs.close();
}
}catch(SQLException e){
e.printStackTrace();
}
try{
if(ps!=null){
ps.close();
}
}catch(SQLException e){
e.printStackTrace();
}
try{
if(conn!=null){
conn.close();
}
}catch(SQLException e){
e.printStackTrace();
}
}
public static void main(String[] args) throws SQLException
{
Connection cc=JDBCUtlTool.getConnection();
if(!cc.isClosed())
System.out.println("Succeeded connecting to the Database!");
Statement statement = cc.createStatement();
String sql = "select * from test2";
ResultSet rs = statement.executeQuery(sql);
while(rs.next()) {
System.out.println(rs.getString("id")+"");
}
}
}
更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java+MySQL數(shù)據(jù)庫程序設(shè)計總結(jié)》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java文件與目錄操作技巧匯總》、《Java操作DOM節(jié)點技巧總結(jié)》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計有所幫助。
相關(guān)文章
MyBatis的@SelectProvider注解構(gòu)建動態(tài)SQL方式
這篇文章主要介紹了MyBatis的@SelectProvider注解構(gòu)建動態(tài)SQL方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08
Springboot如何根據(jù)實體類生成數(shù)據(jù)庫表
這篇文章主要介紹了Springboot如何根據(jù)實體類生成數(shù)據(jù)庫表的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
macOS上使用gperftools定位Java內(nèi)存泄漏問題及解決方案
這篇文章主要介紹了macOS上使用gperftools定位Java內(nèi)存泄漏問題,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07

