jdbc方式连接数据库并执行sql语句

package com.demo;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Demo6 {
static Connection con = null;
private static String urlPath = "jdbc:mysql://127.0.0.1:3306/test";
private static String user = "root";
private static String password = "root";
static ResultSet rs = null;
static PreparedStatement statement = null;
public static void main(String[] args) {
// TODO Auto-generated method stub
//打开连接
openConnection();
con = getConection();
String sql = "select * from test";
try {
statement = con.prepareStatement(sql);
//执行查询
statement.execute();
//关闭连接
closeConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
public static Connection getConection(){
return con;
}
public static void openConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(urlPath,user,password);
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}
}
public static void closeConnection(){

try {
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try{
if(statement != null){
statement.close();
}
}catch(SQLException e){
statement = null;
}finally {
try{
if(con!=null){
con.close();
}
}catch(SQLException e){
con = null;
}
}
}
}

}

posted @ 2023-01-05 11:40  swses  阅读(53)  评论(0编辑  收藏  举报