测试类
package MyJdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCTest {
public static void main(String[] args){
Statement st = null;
ResultSet rs = null;
Connection con = null;
//1.注册驱动
try {
con=JDBCUtil.getCon();
//3.创建statement对象
st = con.createStatement();
//4.执行查询,得到结果集
String sql="select * from _count";
rs = st.executeQuery(sql);
//5.遍历查询每一条记录
while(rs.next()) {
int id=rs.getInt("id");
String name=rs.getString("name");
String sex=rs.getString("sex");
System.out.println(" id="+id+" , name="+name+" , sex="+sex);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//6.释放资源
JDBCUtil.Close(rs, st, con);
}
}
}
工具类进行抽取
package MyJdbc;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtil {
//注册驱动
static String driverClass=null;
static String url=null;
static String user=null;
static String password=null;
static {
//创建一个属性配置对象
Properties pro=new Properties();
//创建输入流
//在工程的根目录下创建对象去读取根目录下的文件
//InputStream is=new FileInputStream("JDBC.properties");//error:系统找不见指定路径,,
//使用类加载器去读取src底下的资源文件
InputStream is=JDBCUtil.class.getClassLoader().getResourceAsStream("JDBC.properties");
//导入输入流
try {
pro.load(is);
//读取属性
driverClass = pro.getProperty("driverClass");
url=pro.getProperty("url");
user=pro.getProperty("user");
password=pro.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
}
public static Connection getCon() {
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user,password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//全路径
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//建立连接
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
//释放资源
public static void Close(ResultSet rs,Statement st,Connection con) {
closeRs(rs);
closeSt(st);
closeCon(con);
}
private static void closeRs(ResultSet rs) {
try {
if(rs != null) {
rs.close();
}
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
rs=null;
}
}
private static void closeSt(Statement st) {
try {
if(st != null) {
st.close();
}
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
st=null;
}
}
private static void closeCon(Connection con) {
try {
if(con != null) {
con.close();
}
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
con=null;
}
}
}
文件内容:读取时注意文件的路径
driverClass = jdbc:mysql:jdbc.Driver
url = jdbc:mysql://localhost/count
user = root
password = 123456
网友评论