java jdbc 的基本操作
1、jdbc介绍
一种执行sql语言的java api
可以对主流的数据库同意访问
极大的减少了程序操作数据库的复杂性
jdbc使用面向对象的方式操作数据
jdbc可以直接调用数据库的存储过程
jdbc操作数据库的效率很高
2、jdbc常用的API
首导入安装jar包,可以去网盘下载 :https://pan.baidu.com/s/16nHzbjxpZ0KQIfL5YtfTDg 提取码:eunc
我已ide java开发工具为例,安装jar包,如图:
File---Projcet Structure---Modukes
点击 “+” 号,选择 点击 JARS or directories---选择jdbc jar包即可。
连接数据库的基本语法:
1、Class.forName(驱动包 例如:“com.mysql.cj.jdbc.Driver”);
//定义Connectioon d对象,连接数据库
2、Connection conn = DriverManager.getConnection(数据库路径,数据库用户名,数据库密码);
例如:conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名称",root,xxxx);
如果运行报已下错误:
The server time zone value ’ й ʱ ’ is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
解决方法:
在mysql中执行
SHOW VARIABLES LIKE ‘%time_zone%’;
SET GLOBAL time_zone="+8:00";
或者在url最后添加:?serverTimezone=GMT%2B8
3、创建PreparedStatement,ResultSet对象
PreparedStatement:预编译的SQL语句的对象
ResultSet : 数据库结果集的数据表,通常通过执行查询数据库的语句生成
基本语法如下:
PreparedStatement ps = null;
ResultSet rs =null;
ps = conn.prepareStatement(SQL语句);
rs = ps.executeQuery ()//;//查询出来的结果集
while(rs.next())
{
System.out.println(rs.getString("数据库字段名"));
}
添加、修改,删除
int row = ps.executeUpdate();//添加、删除、修改 返回的执行完的行数
4、关闭数据库对象连接
关闭的顺序是由里往外关闭
PreparedStatement ps = null;
ResultSet rs =null;
Connection conn = null;
则关闭的顺序是 rs.close(),ps.close(),conn.close();
5、占位符的使用
基本的语法,已添加为例:
String Sql ="insert into test (xxx,xx,xxx) values (?,?,?)";
// 这个问号就是占位符
ps=conn.prepareStatement(Sql );
ps.setString(1,值);
ps.setInt (2,值);
ps.setString(3,值);
int row =ps.executeUpdate();
如果row > 0 :添加成功,否则失败。
使用占位符的好处:
1、占位符的方式效率极高
2、拼写的时候不容易出错
3、防止sql注入
想看jdbc其他api请跳转:https://pan.baidu.com/s/1F6XZhKk-sc2Xc3z0DbMKjw 提取码:ngm8