Jdbc连接数据库(1)

一、连接数据库大体操作

		1、导入jar包	
		2、反射加载驱动
		3、创建连接
		4、创建sql语句
		5、生成Statement对象
		6、执行sql语句
		7、获取结果,遍历ResultSet
		8、关闭连接

二、查询操作详细介绍

//1、导入jar包可以maven的官网去搜索:mysql-connector-java
/**2、反射加载驱动
	mysql5是 :com.mysql.jdbc.Driver;mysql6是:com.mysql.cj.jdbc.Driver */
	Class.forName(com.mysql.cj.jdbc.Driver);
/**3、创建连接
		///user表的属性:id 、username、password、sex	
*/
	String url="jdbc:mysql://localhost:3306/testPro?useUnicode=ture&characterEncoding=UTF8&serverTimezone=GMT%2B8";
	String username="root";
	String password="root";
	Connection conn = DriverManager.getConnection(url,username,password);
//4、生成sql语句
	String sql="select * from user";(数据库testPro存在表 user)
//5、生成Statement对象
	Statement stmt=conn.createStatement();
	常用的是生成  PreparedStatement对象
	PreparedStatement prestmt = conn.prepareStatement(sql);
	如果sql是带参数的sql:select * from user where id=? 
    可以通过prestmt.setString(1,"7");//或则prestmt.setInt(1,"7");(1代表参数索引,从1开始;7 代表id)
//6、执行sql语句
	ResultSet resultset = prestmt.executeQuery();			//查询操作
//7、获取结果,遍历resultset(之后我们会将结果封装在List<Map> 集合里面)
	while(resultset.next()){	//当存在下一个元素的时候	
		///user表的属性:id 、username、password、sex	
		//获取查询到结果的:username,索引从1 开始,不可为0,当心越界 
		System.out.println("username:"+resultset.getString(2));	
	}
//8、关闭连接,jdbc执行需在try{}catch(){}finally{},关闭连接需要在finally中,同时进行判空处理
//遵循    先开启的后关闭  原则
	try {
            if(resultSet!=null){
               resultSet.close();
            }
            if(prestmt !=null){
               prestmt.close();
            }
            if(connection!=null){
               connection.close();
            }
            } catch (SQLException e) {
              e.printStackTrace();
            }
	    }

三、新增、删除、修改、删除

///1、新增操作
        String url="jdbc:mysql://localhost:3306/testPro?useSSL=false";
        String username="root";
        String password="root";
        String driver="com.mysql.cj.jdbc.Driver";
        Connection connection=null;
        PreparedStatement prestmt=null;
        ResultSet resultSet=null;
        int result;
        try {
            //反射加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取连接
            connection = DriverManager.getConnection(url, username, password);
            String sql="insert into user(id ,username ,password,sex) values(?,?,?,?)";
            //生成PreparedStatement,可以防止sql注入
            prestmt=connection.prepareStatement(sql);
            //设置参数
            prestmt.setInt(1,3);
            prestmt.setString(2,"username");
            prestmt.setString(3,"password");
            prestmt.setString(4,"男");
            prestmt.executeUpdate();         //返回执行结果的条数
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
                try {
                    if(resultSet!=null){
                        resultSet.close();
                    }
                    if(prestmt !=null){
                        prestmt.close();
                    }
                    if(connection!=null){
                        connection.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
 ///2、更新操作           
 			String sql="update user set username= ?, password=? where id= ?";
            //生成PreparedStatement,可以防止sql注入
            prestmt=connection.prepareStatement(sql);
            //设置参数
            prestmt.setString(1,"username_update");	//username的值
            prestmt.setString(2,"password_update"); //password的值
            prestmt.setInt(3,3);                    //id的值
            prestmt.executeUpdate();         //返回执行结果的条数
///3、删除操作(与更新类似)
			String sql="delete from user where id=?";	
///4、查询操作(*****全面*****)
    public static void test03(){
        String url="jdbc:mysql://localhost:3306/testPro?useSSL=false";
        String username="root";
        String password="root";
        Connection connection=null;
        PreparedStatement prestmt=null;
        ResultSet resultSet=null;
        try {
            //反射加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取连接
            connection = DriverManager.getConnection(url, username, password);
            String sql="select * from user where id> ? ";
            //生成PreparedStatement,可以防止sql注入
            prestmt=connection.prepareStatement(sql);
            //设置参数
            prestmt.setString(1,"0");   //设置id条件
            resultSet = prestmt.executeQuery();             //返回执行结果
            if(resultSet!=null){
                while (resultSet.next()){
                    //resultSet.next(): 指向返回结果的下一行数据
                    System.out.println(resultSet.getString(1)+resultSet.getString(2));  //通过columnIndex获取每一行的每一列数据
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(resultSet!=null){
                    resultSet.close();
                }
                if(prestmt !=null){
                    prestmt.close();
                }
                if(connection!=null){
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

四、类方法介绍

1、Connection

方法作用
Statement createStatement()创建statment对象
setAutoCommit(Boolean flag)false 将隐式事务改为显示事务,true用隐式事务
commit()自动提交事务
rollback()异常回滚
rollback(SavePoint p)可以手动定义回滚点,rollback可以指定回滚点进行回滚
SavePoint setSavePoint()设置回滚点
close()关闭连接,并释放资源
pareparedStatement(String sql)设置回滚点
SavePoint setSavePoint()返回PreparedStatement对象用于执行预编译SQL语句

2、DriverManager(class)

方法作用
public static Connection getConnection(String url,String user,String password)url中不包含用户名和密码。user用户名;passoword就是密码

3、Driver(interface)
每个驱动程序类必须实现的接口。
4、Statement(interface)

方法作用
close()关闭statment资资源
boolean execute(String sql)执行(更新、查询)sql
ResultSet executeQuery(String sql)执行查询sql
int executeUpdate(String sql)执行更新sql
int[] addBatch(String sql)使用sql批量处理sql
int[] executeBatch()批量执行已添加的sql语句,int[]中存放每个sql语句的影响行数
clearBatch()清空sql语句列表

5、PreparedStatement extends Statement
常用的方法是: boolean execute(String sql)
ResultSet executeQuery(String sql)
int executeUpdate(String sql)
6、ResultSet

方法作用
boolean next()默认resultSet光标在数据第一行以上,当执行next()时,光标下移,如果下移后存在数据,返回true,否则返回false
Object get【类型】(int columnIndex)获取resultSet当前行的,指定索引的字段值,索引从1开始
Object get【类型】(String columnLable)通过字段名获取值,columnLable可以是as后的别名,也可以是字段名称
ResultSetMetaData getMetaData()**获取查询结果的虚拟表的结构(列的类型,列的个数,列字段名)
next()将光标下移
previous()光标上移
first()将光标移动到第一行
last()将光标移动到最后一行
isFirst()判断光标是否在第一行
isLast()判断光标是否在最后一行

五、可能出现的问题

1、Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class iscom.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
原因:

mysql版本是:6以上的,但是加载驱动写的是mysql 5的驱动:Class.forName(“com.mysql.jdbc.Driver”);

mysql5 的驱动:com.mysql.jdbc.Driver; mysql6的驱动:com.mysql.cj.jdbc.Driver
2、 com.mysql.cj.core.exceptions.InvalidConnectionAttributeException: The server time zone value ‘�й���׼ʱ��’ is unrecognized or represents more than one time zone.
时区问题:

可以进行设置mysql时区为东八区(即北京时间):
jdbc:mysql://localhost:3306/bloguseUnicode=ture&characterEncoding=UTF-8&serverTimezone=GMT%2B8 来解决
3、java.sql.SQLException: Parameter index out of range (0 < 1 ).
原因:参数索引越界(从1 开始,但是传递的是 0 )

​ 修改 0 为1 可以解决
4、Exception in thread “main” java.lang.NullPointerException
空指针异常
5、java.sql.SQLException: No value specified for parameter 1
原因:执行的sql包含 ? 占位符, 但是PreparedStatement prestmt 未设置参数

			//设置参数
            prestmt.setInt(1,2);
            prestmt.setString(2,"username");
            prestmt.setString(3,"password");
            prestmt.setString(4,"男");

6、java.sql.SQLIntegrityConstraintViolationException: Duplicate entry ‘2’ for key 'user.PRIMARY’
原因:Duplicate entry(重复 数据录入)

​ 数据库user中已经存在 主键是 2的数据, 导致主键冲突;

解决措施:变 主键2 为数据库不存在的数据、取消数据库主键
7、Incompatible types .Required :sun.rmi.transport.Connection. Found:java.sql.Connection
在这里插入图片描述
原因:Connection包导错了,需要的是:import java.sql.Connection;

​ 但是导入的是:import sun.rmi.transport.Connection;
8、java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
翻译:无法使用executeQuery()发出数据操作语句。

原因:sql语句是insert或则是update或则delete(新增或则更新或则删除操作)

String sql="insert/delete/update......";
PreparedStatement  prestmt=connection.prepareStatement(sql);
	///更新操作无法用:executeQuery,错误的情况:
prestmt.executeQuery();   	
///可以修改为:
prestmt.executeUpdate();   //或则prestmt.execute(); 

**9、com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure **
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
通过 url 与数据库连接失效

(1)检查url是否正确;(2)检查数据库是否开启

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值