JDBC_02_JDBC连接数据库 (INSERT INTO)
JDBC连接数据库 (INSERT INTO)
-
String url="jdbc:mysql://127.0.0.1:3306/employ?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
协议: jdbc:mysql: ip: 127.0.0.1 PORT端口号: 3306 数据库实例: employ UTC: 简称世界统一时间,跟北京时间相比,比北京早8个小时:serverTimezone=UTC 上海时间: Asia/Shanghai
-
代码实例
import java.sql.*;
public class JDBCTest01 {
public static void main(String[] args) {
//创建驱动对象, 用来获取数据库驱动
Driver driver= null;
// 创建连接对象 ,用来获取数据库连接数据
Connection connection=null;
//创建statement对象将,用来保存SQL语句
Statement statement=null;
try {
//1.注册驱动
driver = new com.mysql.cj.jdbc.Driver(); // 给驱动对象赋值
DriverManager.registerDriver(driver); //注册该驱动对象
//2.获取连接
String url="jdbc:mysql://127.0.0.1:3306/employ?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai"; //要连接的数据库的URL
String username="root"; // 数据库用户名
String password="123456"; //数据库密码
connection= DriverManager.getConnection(url,username,password); //给connection连接对象赋值 (URL,用户名,密码)
System.out.println(connection); //com.mysql.cj.jdbc.ConnectionImpl@17776a8
//3.获取数据库操作对象
statement=connection.createStatement() ; // 创建一个statement对象将sql语句发送到数据库
//4.执行SQL语句
String sql= "insert into dept(deptno,dname,loc) values('100','人事部','北京')"; //定义该sql语句
//专门执行DML语句,返回值int类型,表示所影响的记录条数
int count=statement.executeUpdate(sql);
System.out.println(count==1? "数据插入成功": "数据插入失败");
//5.处理查询结果集 只有select需要这一步
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//6.释放资源
//为了保证资源一定被释放,建议在finally语句块中释放资源,并且要遵循从小到大原则
try {
if(statement!=null){
statement.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
if(connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}