1、读取配置文件
1 //Properties集合 流对象读取键值对 2 public static void getNum() throws Exception { 3 Properties p=new Properties(); 4 FileReader f=new FileReader("c:\\root.properties"); 5 p.load(f); 6 f.close(); 7 }
2、properties文件
url:jdbc:mysql://localhost:3306/qy97
name:"root"
password:"root"
3、数据库连接代码
1
package com.aaa.QuDong;
import java.io.FileReader;
import java.sql.*;
import java.util.Properties;
public class SQLEnc_Test {
public static void main(String[] args) throws Exception {
Properties p=new Properties();
//获取文件里边的值
FileReader f=new FileReader("c:\\root.properties");
p.load(f);
String url=p.getProperty("url");
String user = p.getProperty("name");
String root=p.getProperty("password");
//通过值连接数据库
Connection conn = SQLEns.jdbc_enc(url, user, root);
String sql="select * from users where uname like '%郭敬明%'";
System.out.println(conn);
PreparedStatement pre =conn.prepareStatement(sql);
ResultSet rs = pre.executeQuery();
while (rs.next()){
String name = rs.getString(2);
String dsc = rs.getString(5);
System.out.println("姓名:"+name+" 描述:"+dsc);
}
pre.close();
conn.close();
f.close();
}
//Properties集合 流对象读取键值对
public static void getNum() throws Exception {
Properties p=new Properties();
FileReader f=new FileReader("c:\\root.properties");
p.load(f);
f.close();
}
}
4、JDBC封装mysql数据库连接
1 package com.aaa.demo; 2 3 import java.io.FileNotFoundException; 4 import java.io.FileReader; 5 import java.sql.Connection; 6 import java.sql.DriverManager; 7 import java.util.Properties; 8 9 //封装JDBC 10 public class SQLEns { 11 private static Connection conn; 12 public static Connection jdbc_enc(String url, String user, String password){ 13 try { 14 //注册驱动 15 Class.forName("com.mysql.jdbc.Driver"); 16 //获得数据库连接对象 17 conn = DriverManager.getConnection(url, user, password); 18 } catch (Exception e) { 19 } 20 return conn; 21 } 22 }