Last active
August 29, 2017 06:11
-
-
Save fishLite/ecc531cd0e5af5f4aa6add1675f13b1d to your computer and use it in GitHub Desktop.
DB connection code archive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.SQLException; | |
/** | |
* Created by fishLite on 2017/8/29. | |
*/ | |
public class DBConn { | |
private String url; // 存储SQLSever连接路径 | |
private String serverName; // 存储机器的名称 | |
private String portNumber; // 存储端口名称 | |
private String databaseName; // 存储数据库名称 | |
private String userName; // 存储用户名称 | |
private String password; // 存储密码 | |
/* 设置连接数据库相关参数 */ | |
public DBConn() { | |
url = "jdbc:mysql://"; | |
serverName = "localhost"; | |
portNumber = "3306"; | |
databaseName = "shopping"; | |
userName = "root"; | |
password = "fishwolf027"; | |
} | |
/*获取连接数据库路径并返回*/ | |
private String getConnectionUrl() { | |
return url + serverName+ ":" + portNumber + "/" + databaseName; | |
} | |
/* 获取Conncetion对象并返回 */ | |
public Connection getConnection(){ | |
Connection con = null; | |
try{ | |
Class.forName("com.mysql.jdbc.Driver"); | |
con = | |
DriverManager.getConnection(getConnectionUrl() + "?user="+ userName + "&password=" + password); | |
} catch (ClassNotFoundException e) { | |
e.printStackTrace(); | |
System.out.println("getConnection()内部跟踪错误:"+ e.getMessage()); | |
} catch (SQLException e) { | |
e.printStackTrace(); | |
} | |
return con; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment