t通过读取配置文件propertise来获取连接词的url,username,password
ResourceBundle init = ResourceBundle.getBundle("config.demo.demo-jdbc");
String driver = init.getString("jdbc.driver");
String url = init.getString("jdbc.url");
String user = init.getString("jdbc.username");
代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
public class JdbcUtil {
static Connection conn = null; //把连接词配置成为一个单例的模式
public static Connection getConn() {
if(null == conn) {
ResourceBundle init = ResourceBundle.getBundle("config.demo.demo-jdbc");
String driver = init.getString("jdbc.driver");
String url = init.getString("jdbc.url");
String user = init.getString("jdbc.username");
String password = init.getString("jdbc.password");
try {
Class.forName(driver);
//conn = DriverManager.getConnection(url, user, password);
conn = DriverManager.getConnection(url, "root", "root");
System.out.println(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
return conn;
}
//插入数据到数据库
public static void insertData(String sql) {
Connection conn = getConn();
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.
execute(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//使用完statment之后要记得要关闭
if(null != stmt){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
//查询数据库
public static void main(String[] args) {
Connection conn=JdbcUtil.getConn();
//查询
String Select = "select id,msg,time,username,app,operation,object,result,detail from startstopinfo ";
Statement st=null;
ResultSet rs=null;
try {
st = (Statement) conn.createStatement();
rs= st.
executeQuery(Select);
while
(rs.next()){
System.out.print(" "+rs.getInt(1));
System.out.print(" "+rs.getString(2));
System.out.print(" "+rs.getString(3));
System.out.print(" "+rs.getString(4));
System.out.print(" "+rs.getString(5));
System.out.print(" "+rs.getString(6));
System.out.print(" "+rs.getString(7));
System.out.print(" "+rs.getString(8));
System.out.print(" "+rs.getString(9));
System.out.println();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}