分三个文件:
a.执行文件
package com.fill.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.PreparedStatement;
public class Test1 {
public static void findAll(){
//通过工具类获取数据库连接
Connection conn=(Connection)DBUtiles.getConnection();
PreparedStatement ps=null;
ResultSet rs=null;
String sql="select * from admin_sql_inject where 1";
try {
ps=(PreparedStatement) conn.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
System.out.println(rs.getString("name")+'='+rs.getString("pwd"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtiles.close(rs,ps,conn);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
findAll();
}
}
b.配置文件(放到src根目录):
db_zh_CN.properties
jdbc.uname=root
jdbc.pwd=root
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3308/test
c.工具文件
DBUtiles.java
package com.fill.jdbc;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
import java.util.ResourceBundle;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
public class DBUtiles {
public static String URL;
public static String PWD;
public static String UNAME;
public static String DRIVER;
//private static ResourceBundle rb=(ResourceBundle)ResourceBundle.getBundle("db_zh_CN.properties");
//构造方法私有化,防止外面实例化
private DBUtiles(){
}
//加载驱动放在只会执行一次的地方
static{
Locale locale1 = new Locale("zh", "CN");
ResourceBundle rb = ResourceBundle.getBundle("db", locale1);
//读取配置文件
URL=rb.getString("jdbc.url");
UNAME=rb.getString("jdbc.uname");
PWD=rb.getString("jdbc.pwd");
DRIVER=rb.getString("jdbc.driver");
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//获取数据库连接的方法
public static Connection getConnection(){
Connection conn=null;
try {
conn=(Connection) DriverManager.getConnection(URL,UNAME,PWD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
//关闭连接
public static void close(ResultSet rs,PreparedStatement stat,Connection conn){
try {
if(rs!=null) rs.close();
if(stat!=null)stat.close();
if(conn!=null)conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void close(ResultSet rs, PreparedStatement ps, java.sql.Connection conn) {
// TODO Auto-generated method stub
try {
if(rs!=null) rs.close();
if(ps!=null)ps.close();
if(conn!=null)conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}