通过文件中配置信息创建数据库连接
如果像文章 http://blog.csdn.net/xiaolangfanhua/article/details/52476211 中所述那样,每次要连接数据库时都手动设置 drivers 、url 、username 、password等信息是非常繁琐的,而且还容易出错,我们可以把这些信息以properties的形式配置创建在一个properties的文件中,这样每次要连接数据库时直接在文件中读取这些信息,既方便又不容易出错。
首先配置properties文件:
文件中需要配置的量有:drivers 、url 、username 、password
例如:
1、文件内容:
jdbc.drivers=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/publicationdb? user=root&password=123456
jdbc.username=root
jdbc.password=123456
2、文件路径:
“F:\Projects\Mysql\database.properties”
这个路径在连接的时候需要用到。
以此创建数据库连接并进行操作的实例代码如下:
import java.nio.file.*;
import java.io.*;
import java.util.*;
import java.sql.*;
public class TestDB {
/*
* 用于在database.properties 文件中读取链接参数,连接到数据库
* 并执行相关数据库语言,创建数据库
*/
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
try{
runTest();
}catch(SQLException ex){
for(Throwable t:ex)
{
t.printStackTrace();
}
}
}
public static void runTest() throws SQLException, IOException
{
try(Connection conn=getConnection())
{
Statement stat=conn.createStatement();
stat.executeUpdate("CREATE TABLE Greetings (Message CHAR(20))");
stat.executeUpdate("INSERT INTO Greetings VALUES('Hello, World!')");
try(ResultSet result=stat.executeQuery("SELECT * FROM Greetings"))
{
if(result.next())
{
System.out.println(result.getString(1));
}
stat.executeUpdate("DROP TABLE Greetings");
}
}
}
public static Connection getConnection() throws IOException, SQLException
{
Properties props=new Properties();
try(InputStream in=Files.newInputStream(Paths.get("F:\\Projects\\Mysql\\database.properties")))
{
props.load(in);
}
String drivers=props.getProperty("jdbc.drivers");
if(drivers!=null) System.setProperty("jdbc.drivers",drivers);
String url=props.getProperty("jdbc.url");
String username=props.getProperty("jdbc.username");
String password=props.getProperty("jdbc.password");
return DriverManager.getConnection(url,username,password);
}
}