前一段时间学完了mysql现在在学jdbc感觉还可以,但是JAVA基础部分(异常)还是差点意思,明天学习线性代数,异常和jdbc剩余部分。
1.DriverManager:驱动管理对象 注册驱动 获取数据库连接 static Connection getConnection(String url,String user,String password) url:指定连接的路径 写法:jdbc:mysql://ip地址:端口号/数据库名称 细节(若是本地连接):jdbc:mysql:///数据库名称 2.Connection:数据库连接对象 1.获取执行sql的对象 Statement createStatement() PreparedStatement prepareStatement(String sql) 2.管理事务 开启事务:void setAutoCommit(boolean autoCommit)调用方法设置参数为false,开启事务 提交事务:void commit() 回滚事务:rollback() 3.Statement:执行sql的对象 1.boolean execute(String sql):可以执行任意sql 2.int executeUpdate(String sql)执行DML语句(insert,update,delete)ddl(create drop alter) 返回值:影响的行数 返回值大于0==success 3.ResultSet executeQuery(String sql)执行ddl语句,查询语句 4.ResultSet:结果集对象 5.PrepareStatement:执行sql对象
添加对象示例代码
//添加张。。对象
public class jdbcdemo02 {
public static void main(String[] args) {
Statement stmt = null;
Connection conn = null;
try{
Class.forName("com.mysql.cj.jdbc.Driver");//注册驱动 mysql5之后再services中写过注册
//定义sql
String sql = "insert into account values (null,'张润琪',10000)";
//获取Connection对象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/zzt?serverTimezone=GMT&useSSL=false","root","root");
//获取执行sql 的对象statement
stmt = conn.createStatement();
//执行sql
int count = stmt.executeUpdate(sql);// count影响行数
System.out.println(count);
if(count>0)
System.out.println("添加成功");
else
System.out.println("添加失败");
}
catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}
finally{
if(stmt!=null)
try{
stmt.close();
}catch(SQLException e){
e.printStackTrace();
}
if(conn!=null)
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
更新示例部分代码
public class jdbcdemo03 {
public static void main(String[] args) {
Statement stmt = null;
Connection conn = null;
//注册驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver");
//获取连接对象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/zzt?serverTimezone=GMT&useSSL=false","root","root");
//定义sql
String sql = "update account set name = '张润琦' where id =5 ";
//获取执行sql对象
stmt = conn.createStatement();
//执行sql
int count = stmt.executeUpdate(sql);//获取影响行数
if(count>0){
System.out.println("修改成功");
}
else{
System.out.println("修改成功");
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
finally {
if(stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}