MySql连接数据库——代码
按步骤
1、写配置文件db.properties
Oracle connection
url=jdbc:oracle:thin:@localhost:1521:orcl
user=scott
password=tiger
driver=oracle.jdbc.driver.OracleDriver
MySql connection
url=jdbc:mysql://localhost:3306/test #解释其中的test为连接MySQL数据库的用户名,默认为root:
user=root
password=tiger
driver=com.mysql.jdbc.Driver
此配置文件中的注释符号为#
2. DBUtil类--连接数据库
public class DBUtil {
private static Connection conn;
private static String driver;
private static String url;
private static String user;
private static String password;
private DBUtil(){}
static {
Properties pt = new Properties();
InputStream is;
try {
// is = new FileInputStream(new File("file/db.properties"));
is = DBUtil.class.getResourceAsStream("/db.properties");//用以上两种方法都可以,只是配置文件的位置不同。
pt.load(is);
url = pt.getProperty("url");
user = pt.getProperty("user");
password = pt.getProperty("password");
driver = pt.getProperty("driver");
Class.forName(driver);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection(){
if(null == conn){
try {
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return conn;
}
}
3、测试类
public class test {
ResultSet rs = null;
@Test
public void getConn() throws SQLException{
Connection conn = DBUtil.getConnection();
// String sql = "select * from test_01 ";
// String sql = "insert into test_01(userName,sex) values('rose','Lao不死');";
String sql = "delete from test_01 where userName = 'zhangsan';";
sql = "update test_01 set userName = 'jack123' where userName = 'jack'; ";
PreparedStatement ps = conn.prepareStatement(sql);
int count = ps.executeUpdate();
System.out.println(count);
// rs = ps.executeQuery();
//
// while(rs.next()){
// System.out.println(rs.getInt(1)+","+rs.getString(2)+","+rs.getString(3));
// }
}
}
注意:
1.加入oracle,MySQL数据库的驱动jar包之后,要对其add to build path.
2.对于获取配置文件的db.roperties还有第三种写法,就是重写一个config类,继承properties,读写文件配置。
代码如下:
public class DBConfig extends Properties{
private static DBConfig dbConfig = null;
private DBConfig() throws IOException{
init();
}
private void init() throws IOException {
InputStream is = DBConfig.class.getClassLoader().getResourceAsStream("db.properties");
this.load(is);
}
public static DBConfig getDBConfigInstance() throws IOException{
if(dbConfig == null){
dbConfig = new DBConfig();
}
return dbConfig;
}
}