JDBC(java database connection)
/**
* jdbc 四大参数
* driverClassName : com.mysql.jdbc.Driver
* url : jdbc:mysql://localhost:3306/database
* username : root
* password : yuxing2012
*
*/
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/demo";
String username= "root";
String password = "yuxing2012";
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println(connection);
Statement
- executeUpdate(String sql ); // DDL DML
- executeQuery(String sql);
Statement statement = connection.createStatement();
String sql = "INSERT INTO user(user_name,user_number) VALUES('dapi_"+new Random().nextInt(200)+"','12101010320')";
int i = statement.executeUpdate(sql);
System.out.println("i "+i);
//执行查询
/**
* 1 得到connection
* 2 得到Statement
* 3 解析查询返回的表格对象
*/
String querySql = "SELECT * FROM user";
ResultSet resultSet = statement.executeQuery(querySql);
System.out.println("resultSet "+resultSet);
resultSet.beforeFirst();//第一条记录的前面
while(resultSet.next()){
int id = resultSet.getInt("user_id");
String name = resultSet.getString("user_name");
String number = resultSet.getString("user_number");
System.out.println("id "+id+" name "+name+" number "+number);
}
resultSet.close();
statement.close();
connection.close();
PreparedStatement
String inSql = "INSERT INTO user(user_name,user_number) VALUES(?,?)";
PreparedStatement prepareStatement = connection.prepareStatement(inSql);
prepareStatement.setString(1,"dapi");
prepareStatement.setString(2,"12101010320");
int update = prepareStatement.executeUpdate();
System.out.println("update "+update);
Transation
connection.setAutoCommit(false);
// ..do something
connection.commit();
//or
connection.rollback();
//事务的隔离级别
connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
DBCP
- 依赖的jar commons-dbcp.jar commons-pool.jar
BasicDataSource source = new BasicDataSource();
source.setDriverClassName("");
source.setUrl("");
source.setUsername("");
source.setPassword("");
source.setMaxWaitMillis(2000);
Connection connection2 = source.getConnection();
connection2.close(); // to the pool
C3P0
- 依赖的jar c3p0.jar mchange-commons.jar
//c3p0
ComboPooledDataSource source2 = new ComboPooledDataSource();
Nothing is certain in this life. The only thing i know for sure is that. I love you and my life. That is the only thing i know. have a good day
网友评论