Jdbc连接数据库是经常用到的方法,本文总结下,以备后用:
首先,把数据库连接信息写入配置文件:database.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=root
接着写获取连接的实现
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class JdbcConn {
public static Connection getConnection(){
//连接MySql数据库,用户名和密码都是root
Connection conn = null;
Properties properties = getprop();
String driverString = properties.getProperty("driver");
String dburl = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
try{
Class.forName("com.mysql.jdbc.Driver");
Class.forName(driverString);
conn = DriverManager.getConnection(dburl , username , password ) ;
}catch(SQLException se){
System.out.println("数据库连接失败!");
se.printStackTrace() ;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}
private static Properties getprop() {
Properties properties = new Properties();
try {
InputStream inputStream = Object.class.getResourceAsStream("/database.properties");
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return properties;
}
}
最后测试连接是否成功
public static void main(String[] args) {
String sql = "select * from user limit 2";
Connection conn = null;
ResultSet rs = null;
PreparedStatement pstmt = null;
try{
conn = JdbcConn.getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()){
System.out.println(rs.getString(2));
}
}catch(Exception e){
e.printStackTrace();
}finally{
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
本文参考文章:http://zheng0324jian.iteye.com/blog/1176932

被折叠的 条评论
为什么被折叠?



