public class JDBCDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//连接数据库
String url = "jdbc:mysql://10.30.59.136:3306/wy?serverTimezone=GMT"; //serverTimezone=GMT表示设置时区
String username = "root";
String password = "123456";
Connection con = DriverManager.getConnection(url,username,password);
//获取执行sql语句的对象并且执行sql语句
String sql = "select * from zhibo";
Statement stmt = con.createStatement();
ResultSet resultSet = stmt.executeQuery(sql);
//当resultSet.next()有值时为true否则为flase
while (resultSet.next()){
System.out.println(resultSet.getString("game_name")+","+resultSet.getString("name")+","+resultSet.getString("title")); //获取表中的game_name字段
}
//释放资源
stmt.close();
con.close();
}
}
Connection
Connection con = DriverManager.getConnection(url,username,password); //获取数据库对象
con.setAutoCommit(false); //开启事务
con.commit(); //提交事务
con.rollback(); //回滚事务
//可以用try当发生错误时回滚事务
Statement
stmt.executeUpdate(sql); //执行增删改操作,返回Int类型为受影响条数
stmt.executeQuery(sql); //执行查操作,返回一个ResultSe对象
ResultSe
resultSet.next() //判断下一行有没有数据,有返回true,没有返回flase
resultSet.getString("name") //获取字段name,get后面类型为表中字段类型