java链接MYSQL数据库并实现查找数据代码如何写?

2024-11-01 14:36:13
推荐回答(1个)
回答(1):

首先创建一个连接工厂import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;public class ConnectionFactory {
private Connection conn=null;
private Statement stmt=null;
private ResultSet rs=null;
public ConnectionFactory() {
super();
// TODO Auto-generated constructor stub
} public void OpenConn() throws Exception{
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url="jdbc:mysql://127.0.0.1:3306/guestbook";
String user="root";
String password="root";
conn=DriverManager.getConnection(url,user,password);
}catch(Exception e){
System.out.println("创建链接抛出异常为:"+e.getMessage());
}

} public ResultSet executeQuery(String sql) throws Exception{
try{
stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs=stmt.executeQuery(sql);

}catch(Exception e){
System.out.println("执行查询抛出的异常为:"+e.getMessage());
}
return rs;
} public void close() throws Exception{
try{
rs.close();
stmt.close();
conn.close();
}catch(Exception e){
System.out.println("关闭对象抛出的异常:"+e.getMessage());
}
} }
测试类 import java.sql.ResultSet;public class TestJDBC {
public static void main(String[] args) {
ConnectionFactory c= new ConnectionFactory();
try {
c.OpenConn();
String sql="select * from tb_guestbook";
ResultSet rs=c.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getString(2));
}
c.close();
System.out.println();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}