Java JDBC 连接数据库的简单使用

连接数据库一般需要的以下基本信息:

url: 数据库URL

ip:数据库所在服务器

dbName:数据库名

user:用户名

password:密码

sqlDriver:驱动

需要导入sql类:import java.sql.*;

1.连接数据库(以MysQL 8.0为例)

try {
            String driverStr = "com.mysql.cj.jdbc.Driver";
            serverIP = "127.0.0.1";
            user = "root";
            password = "123456";
            dbName = "test";
            dbUrl = "jdbc:mysql://" + serverIP + "/" + dbName  + "?useUnicode=true&characterEncoding=utf-8&useSSL=false&amp&serverTimezone=UTC";
            //加载驱动
            Class.forName(driverStr);
            //获取连接对象
            Connection connection = DriverManager.getConnection(dbUrl,user,password);
            conInfo.setText("连接成功"); 
            //最后关闭
            connection.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

2.Statement对象

Statement对象用于执行无参数的SQL语句,

2.1 boolean execute (String SQL) : 如果可以检索到ResultSet对象,则返回一个布尔值true; 否则返回false。使用此方法执行SQLDDL语句或需要使用真正的动态SQL,可使用于执行创建数据库,创建表的SQL语句等等。
2.2 int executeUpdate (String SQL): 返回受SQL语句执行影响的行数。一般用于INSERT,UPDATE或DELETE语句。
2.3 ResultSet executeQuery(String SQL):返回一个ResultSet对象。 一般用于SELECT语句。

//创建Statement对象
statement = connection.createStatement();
//获取结果集
ResultSet resultSet = statement.executeQuery("select * from user");
//将结果集打印出来
while (resultSet.next()){
      System.out.println(resultSet.getString(1) + resultSet.getString(2) + resultSet.getString(3));
       }
//关闭
statement.Close();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值