package dao;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class JdbcTest {
private String jdbcDriver;
private String jdbcUrl;
private String userName;
private String password;
private Properties pro;
private Connection connection;
private PreparedStatement preSt;
public JdbcTest() {
pro = new Properties();
try {
pro.load(new FileInputStream("D:\\Java\\代码\\jsp_demo\\src\\main\\resources\\db.properties"));
jdbcDriver = pro.getProperty("jdbcDriver");
jdbcUrl = pro.getProperty("jdbcUrl");
userName = pro.getProperty("user");
password = pro.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
}
public void getConnection() {
try {
Class.forName(jdbcDriver);
connection = DriverManager.getConnection(jdbcUrl, userName, password);
connection.setAutoCommit(false);
connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void insert() {
String sql = "insert into user values(?,?);";
try {
preSt = connection.prepareStatement(sql);
preSt.setString(1, "WELCOME");
preSt.setInt(2, 99);
int i = preSt.executeUpdate();
System.out.println("修改了多少行: " + i);
} catch (SQLException e) {
e.printStackTrace();
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
public void select() {
String sql = "select * from user where password = ? and name = ?;";
System.out.println(sql);
try {
preSt = connection.prepareStatement(sql);
preSt.setInt(1, 9);
preSt.setString(2, "name or shortname");
System.out.println(preSt);
ResultSet resultSet = preSt.executeQuery();
Savepoint point1 = connection.setSavepoint("point1");
while (resultSet.next()) {
System.out.println("name: " + resultSet.getString(1)
+ " password: " + resultSet.getString(2)
);
}
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
public void commit() {
try {
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void close() {
try {
if (connection != null) {
connection.close();
connection = null;
}
if (preSt != null) {
preSt.close();
preSt = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
JdbcTest jdbcTest = new JdbcTest();
try {
jdbcTest.getConnection();
jdbcTest.insert();
} finally {
jdbcTest.commit();
if (jdbcTest != null) {
jdbcTest.close();
jdbcTest = null;
}
}
}
}