這裡是使用mysql資料庫。
使用一個mysql.ini檔案(就是一個properties檔案)來儲存資料庫連接配接資訊,這是比較成熟的做法———但需要把應用程式
從開發環境移植到生産環境時,無須修改源代碼,隻需要修改mysql.ini配置檔案即可。
凡凡第一看到時候,以為是mysql.ini自帶檔案,就把mysql裡的複制過去。(o(╯□╰)o囧了!!)
下圖展示檔案及其存放位置。
建立檔案:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI0gTMx81dsQWZ4lmZf1GLlpXazVmcvwFciV2dsQXYtJ3bm9CX9s2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xCMy81dvRWYoNHLwEzX5xCMx8FesU2cfdGLwMzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5SO2YzN3YzNzkDZyImM1ITNzYzX2ATNwYTMxIzLcBTMyIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.png)
檔案内容:
檔案存放:
①與所要使用類的同級
②直接放在src下
在web中放在src的配置檔案會直接加載到classes中
而Java的properties檔案需要放到classpath下面,這樣程式才能讀取到,有關classpath實際上就是java類或者庫的存放路徑,在java工程中,properties放到class檔案一塊
原因:讀取檔案是使用類加載器,而類加載器讀取檔案,預設是在src下。
class檔案一塊
操作:
使用如下:
public class ExecuteDDL
{
private String driver;
private String url;
private String user;
private String pwd;
public void initParam(String paramFile) throws Exception
{
Properties props= new Properties();
props.load(new FileInputStream(paramFile));
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
pwd = props.getProperty("pwd");
}
public void createTable(String sql) throws Exception
{
Class.forName(driver);
try(
Connection conn = DriverManager.getConnection(url, user, pwd);
Statement stmt = conn.createStatement())
{
stmt.executeUpdate(sql);
}
}
public static void main(String []args) throws Exception
{
ExecuteDDL ed = new ExecuteDDL();
ed.initParam("src/com/yyf/JDBC/db.properties");
ed.createTable("create table jdbc_test" +
"(jdbc_id int auto_increment primary key,"
+"jdbc_name varchar(255)"
+"jdbc_desc text);"
);
System.out.println("成功");
}
}