import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;
public class testMysql {
public static void main(String[] args){
testMysqlConnection();
}
public static void testMysqlConnection()
{
Connection con = null;// 创建一个数据库连接
PreparedStatement pre = null;// 创建预编译语句对象,一般都是用这个而不用Statement
ResultSet result = null;// 创建一个结果集对象
try
{
Class.forName("com.mysql.jdbc.Driver");// 加载Oracle驱动程序
System.out.println("开始尝试连接数据库!");
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8";
String user = "root";// 用户名,系统默认的账户名
String password = "123456";// 你安装时选设置的密码
long startTime = System.currentTimeMillis();
con = DriverManager.getConnection(url, user, password);// 获取连接
con.setAutoCommit(false);
// String maxUpdateTimesql = "select max(TOPIC_UPDATE_TIME) as maxTime from t29e0000_02aa003 "+ "where OPERATETYPE = ?";
// PreparedStatement ps = con.prepareStatement(maxUpdateTimesql);
// ps.setString(1, "I");
// result = ps.executeQuery();
//result 初始游标为head,移动next到第一个记录
/* while(result.next()){
//Date maxTime = result.getDate("maxTime");
Date maxTime = result.getDate(1);
System.out.println("============maxTime:"+ maxTime.toLocaleString());
}*/
String iSql = "INSERT INTO user(name,age)VALUES(?,?)";
PreparedStatement ps =con.prepareStatement(iSql);
ps.setString(1, "jack");
ps.setInt(2, 23);
ps.execute();
ps.setString(1, "mark");
ps.setInt(2, 67);
ps.execute();
String uSql = "UPDATE user SET name = ?,age=? WHERE id=?";
ps = con.prepareStatement(uSql);
ps.setString(1, "donald");
ps.setInt(2, 28);
ps.setInt(3, 11);
ps.executeUpdate();
long endTime = System.currentTimeMillis();
System.out.println("============time:"+ (endTime-startTime));
System.out.println("============hashCode:"+ con.hashCode());
if(!con.isClosed()){
System.out.println("============连接成功!");
}
con.commit();
}
catch (Exception e)
{
con.rollback();
System.out.println("=============连接失败:"+e.getMessage());
e.printStackTrace();
}
finally
{
try
{
// 逐一将上面的几个对象关闭,因为不关闭的话会影响性能、并且占用资源
// 注意关闭的顺序,最后使用的最先关闭
if (result != null)
result.close();
if (pre != null)
pre.close();
if (con != null)
con.close();
System.out.println("数据库连接已关闭!");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
JDBC PreparedStatement 的用法
最新推荐文章于 2023-10-03 23:29:28 发布