一、JDBC编写步骤
1.注册驱动 -》加载Driver类
2.获取连接 -》得到Connection
3.执行增删改查 -》发送SQL给数据库执行
4.释放资源 -》关闭连接
二、JDBC连接方式1:
获取Driver实现类的对象,属于静态加载,依赖性强,不灵活。
jar包下载地址:https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.37
-- 在jun_db02数据库中
CREATE TABLE actor(-- 演员表
id INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(32) NOT NULL DEFAULT'',
sex CHAR(1)NOT NULL DEFAULT'女',
borndate DATETIME,
phone VARCHAR(32)
);
SELECT*FROM actor
package com.jun.jdbc;
import com.mysql.jdbc.Driver;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
*jdbc程序,完成简单的操作
*/
public class Jdbc01 {
public static void main(String[] args) throws SQLException {
//配置:在项目下创建一个文件夹:libs
//把mysql.jar包拷贝过来,在Add as Library加入到项目里
//注册驱动
//创建driver对象
Driver driver = new Driver();
//得到连接
//jdbc:mysql://表示协议规定好的,通过jdbc的方式连接数据库
//localhost 主机,也可以用ip地址
//3366 nysql监听端口
//jun_db02连接mysql dbms的某个数据库
//mysql的连接本质就是socket连接
String url = "jdbc:mysql://localhost:3366/jun_db02";
//把用户名和密码放到Properties对象中
Properties properties = new Properties();
//user和password都是规定好的,后面根据自己的数据库写
properties.setProperty("user","root");//用户
properties.setProperty("password","123456");//密码
Connection connect = driver.connect(url, properties);
//执行sql
//String sql = "insert into actor values(null,'赵本山','男','1963-12-12','123456')";
//String sql = "update actor set name ='小沈阳'where id=1";
String sql = "delete from actor where id=1";
//statement用于执行静态的sql语句并返回生成结果的对象
Statement statement = connect.createStatement();
int rows = statement.executeUpdate(sql);//假如dml语句,返回的就是影响行数
System.out.println(rows>0 ?"成功":"失败");
//关闭连接
statement.close();
connect.close();
}
}