mysql怎么连接到数据库_Java如何连接到数据库(MySQL)?

如何使用JDBC连接到MySQL数据库? 假定数据库名称是:testdb,其中有一个表:employee,这个表中有4条记录。

创建数据库表的语句 –

use testdb; create table if not exists employees ( id int not null, age int not null, first varchar (255), last varchar (255) ); INSERT INTO Employees VALUES (100, 28, 'Max', 'Su'); INSERT INTO Employees VALUES (101, 25, 'Wei', 'Wang'); INSERT INTO Employees VALUES (102, 30, 'Kida', 'Su'); INSERT INTO Employees VALUES (103, 28, 'Kobe', 'Bryant');

以下示例使用getConnection(),createStatement()和executeQuery()方法连接到数据库并执行查询。

package com.yiibai; import java.sql.*; public class JdbcConn { public static void main(String[] args) { String JDBC_DRIVER = "com.mysql.jdbc.Driver"; String DB_URL = "jdbc:mysql://localhost/testdb?useSSL=false"; String User = "root"; String Passwd = "123456"; try { Class.forName(JDBC_DRIVER); } catch (ClassNotFoundException e) { System.out.println("Class not found " + e); } int total_rows = 0; try { Connection con = DriverManager.getConnection(DB_URL, User, Passwd); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM employees"); while (rs.next()) { total_rows++; } System.out.println("There are " + total_rows + " records in the table"); } catch (SQLException e) { System.out.println("SQL exception occured" + e); } } }

上述代码示例将产生以下结果(结果可能会有所不同)。

There are 4 records in the table

注:如果JDBC驱动程序安装不正确,将获得ClassNotfound异常。

Class not found java.lang.ClassNotFoundException: com.mysql.jdbc.Driver JDBC Class found SQL exception occuredjava.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/testdb

¥ 我要打赏 纠错/补充 收藏

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值