通过JDBC远程连接云端数据库
我的云數(shù)據(jù)庫是使用的Mariadb,布局在騰訊云上。
今天第一天學(xué)習(xí)JDBC,實現(xiàn)了使用JDBC遠(yuǎn)程連接云數(shù)據(jù)庫,實現(xiàn)方式可能會有些低級,特此記錄。
一、配置環(huán)境
首先是下載并配置mysql-connector-java-5.1.47包,由Mysql提供,
? ? ? 下載地址:https://pan.baidu.com/s/1Au_l2JfhrJmGqRYYA7UEaA 提取碼: y3cx?
? ? ? 使用手冊:https://dev.mysql.com/doc/connector-j/5.1/en/
解壓.zip后復(fù)制*bin.jar文件到工程里,然后右鍵 Build Path 加入工程,效果如圖
二、遠(yuǎn)程連接數(shù)據(jù)庫
這一步首先要確認(rèn)云端數(shù)據(jù)庫用戶是否支持遠(yuǎn)程連接,這里可以參看教程:https://blog.csdn.net/Doit_kang/article/details/84260261
這是初始的方法,耦合性比較高:給出的代碼只是方法代碼,用到的包可根據(jù)報錯自行import
/*** 獲取與云端mysql數(shù)據(jù)庫的連接,此方法耦合性較高* @throws SQLException*/@Testpublic void testJDBC() throws SQLException {Driver driver = new com.mysql.jdbc.Driver();String url ="jdbc:mysql://云服務(wù)器ip地址:3306/訪問的數(shù)據(jù)庫名稱";Properties info = new Properties();info.setProperty("user", "root");//數(shù)據(jù)庫登陸用戶名info.setProperty("password", "123456");//個人的數(shù)據(jù)庫登陸密碼Connection connention = driver.connect(url, info);System.out.println(connention);}修改后的工具類方法
/*** DriverManager:驅(qū)動的管理類* 類方法,在不修改源代碼的情況下,通過修改配置文件,* 可以獲取任何數(shù)據(jù)庫的連接,從而達(dá)到解耦的目的* @return * @throws Exception */public static Connection getConnection() throws Exception {String jdbcUrl = null;String driverClass = null;String user = null;String password = null;//創(chuàng)建輸入流來讀取 src 下的 jdbc.propreties 文件,注意文件路徑InputStream in = JDBCTools.class.getClassLoader().getResourceAsStream("com/learning/JDBC/jdbc.properties");//從輸入字節(jié)流(in)讀取屬性列表(鍵和元素對)。 Properties properties = new Properties();properties.load(in);//使用此屬性列表中指定的鍵搜索屬性,獲取值jdbcUrl = properties.getProperty("jdbcUrl");driverClass = properties.getProperty("driver");user = properties.getProperty("user");password = properties.getProperty("password");in.close(); //關(guān)閉輸入流//加載數(shù)據(jù)庫驅(qū)動程序(對應(yīng) Driver 實現(xiàn)類中有注冊驅(qū)動的靜態(tài)代碼塊)Class.forName(driverClass);//獲取與數(shù)據(jù)庫的連接Connection connection = DriverManager.getConnection(jdbcUrl, user, password);return connection;}jdbc.properties文件里的內(nèi)容:
jdbcUrl=jdbc:mysql://45.40.195.241:3306/myFirstDb
driver=com.mysql.jdbc.Driver
user=個人數(shù)據(jù)庫登陸用戶名
password=個人數(shù)據(jù)庫登陸密碼
?
總結(jié)
以上是生活随笔為你收集整理的通过JDBC远程连接云端数据库的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ghost linux引导修复工具,Gh
- 下一篇: 时间字段加一秒_Mysql自动加1秒的问