简单连接MySQL
//1、注册驱动
//反射把这个类加载到内存
Class.forName("com.mysql.jdbc.Driver");
//2、获取连接
String url = "jdbc:mysql://localhost:3306/dashuju2?useSSL=false&serverTimezone=UTC";
String user = "root";
String pass = "123456";
Connection conn = DriverManager.getConnection(url,user,pass);
//3、定义SQL语句
String sql = "UPDATE `counts` SET `money` = 10000 WHERE user_id = 1;";
//4、执行SQL对象
Statement stat = conn.createStatement();
//5、执行SQL
int i = stat.executeUpdate(sql);//返回受影响的行数
System.out.println(i);
// 释放资源
stat.close();
conn.close();
MySQL8版本连接方式(需要修改URL和Class.forName)
url = "jdbc:mysql://localhost:3306/yinhang?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8"
Class.forName("com.mysql.cj.jdbc.Driver")
connection 事务管理
开启事务:setAutoCommit(boolean autoCommit);
true为自动提交,false为手动提交
提交事务:commit()
回滚事务:rollback()
//2、获取连接
String url = "jdbc:mysql://localhost:3306/dashuju2?useSSL=false&serverTimezone=UTC";
String user = "root";
String pass = "123456";
Connection conn = DriverManager.getConnection(url,user,pass);
//4、执行SQL对象
Statement stat = conn.createStatement();
//5、执行SQL
//3、定义SQL语句
try {
//创建事务
conn.setAutoCommit(false);
String sql = "UPDATE `counts` SET `money` = 100 WHERE user_id = 1;";
int i = stat.executeUpdate(sql);//返回受影响的行数
System.out.println(i);
String sql1 = "UPDATE `counts` SET `money` = 10000 WHERE user_id = 2;";
int i1 = stat.executeUpdate(sql);//返回受影响的行数
System.out.println(i1);
//没有异常就提交事务
conn.commit();
} catch (Exception e) {
//执行失败就回滚事务
conn.rollback();
e.printStackTrace();
}
// 释放资源
stat.close();
conn.close();
statement 执行SQL语句
int executeUpdate() 执行改、删、增
ResultSet executeQuery() 执行查
这个是最常用的,获取查询结果的两个方法
boolean next()
将光标向前移动一步,判断当前行是否为有效行。
getxxx
xxx代表数据类型:如int getInt(参数);
String getString(参数)
参数:
int:列的编号,从一开始
string:列的名称0
public void test1() throws Exception {
//2.获取连接
String url = "jdbc:mysql://localhost:3306/dashuju2?useSSL=false&serverTimezone=UTC";
String user = "root";
String pass = "123456";
Connection cnn = DriverManager.getConnection(url,user,pass);
//3、定义sql
String sql = "select * from counts";
// 4、获取statement
Statement sta = cnn.createStatement();
//5.执行SQL语句
ResultSet re = sta.executeQuery(sql);
//6.处理结果
//6.1、光标向下移动一行,并且判断是否有数据
while (re.next()){
//6.2、获取数据 getxxx()
/*
方法一
int id = re.getInt(1);
String name = re.getString(2);
double money = re.getDouble(3);
*/
//方法二
int id = re.getInt("user_id");
String name = re.getString("user_name");
double money = re.getDouble("money");
System.out.println(id);
System.out.println(name);
System.out.println(money);
}
//释放资源
re.close();
sta.close();
cnn.close();
}