package jdbc01;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class jdbcTool {//连接数据库和关闭流的工具类
public Connection connect() throws IOException, SQLException {
Properties properties = new Properties();
properties.load(new FileInputStream("mysql02.properties"));
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
Connection connection = DriverManager.getConnection(url,user,password);
return connection;
}
public void ShutDown(Connection connection) throws SQLException {
connection.close();
}
}
package jdbc01;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class jdbcText {//工具类练习
public static void main(String[] args) throws SQLException, IOException {
Scanner input = new Scanner(System.in);
jdbcTool jdbcTool = new jdbcTool();
Connection connect = jdbcTool.connect();
System.out.println("请输入要删除的用户名:");
String name = input.nextLine();
String sql = "delete from admin where name=?";
PreparedStatement preparedStatement = connect.prepareStatement(sql);
preparedStatement.setString(1,name);
int j = preparedStatement.executeUpdate();
System.out.println(j>0?"删除成功":"删除失败");
jdbcTool.ShutDown(connect);
}
}
基础内容就剩去一个连接过程
package jdbc01;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class jdbcUtil {//德鲁伊工具类
private static DataSource ds;
static {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("src\\druid.properties"));
ds= DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
//编写方法
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//编写关闭连接,不是直接关闭而是把连接放回连接池
public static void close(ResultSet resultSet, Statement statement,Connection connection){
try {
if(resultSet!=null){
resultSet.close();
}
if(statement!=null){
statement.close();
}
if(connection!=null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}