1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 使用jdbc驱动连接mysql_使用jdbc连接mysql数据库

使用jdbc驱动连接mysql_使用jdbc连接mysql数据库

时间:2020-04-13 17:12:23

相关推荐

使用jdbc驱动连接mysql_使用jdbc连接mysql数据库

1.提供mysql的jdbc驱动(我的博客文件里提供了驱动jar包)

2.使用IDEA工具,把jar包添加到项目里(具体步骤如下)

1)打开模块设置

2)选择libraries功能,点击+号,选择java,找到jar包所在的目录位置,添加即可。

3)jar包添加后,项目下方的External Libraries的目录下,可以看到已经添加完成的jar包。

3.创建jdbc类

public class JdbcUtils {

public static void main(String[] args) throws SQLException {

Connection connection = null; Statement statement = null; ResultSet resultSet = null;

//1.加载jdbc驱动类

try {

//用反射机制,获取mysql-jdbc驱动中的Driver类。com.mysql.jdbc.Driver代表mysql-jdbc驱动中com.mysql.jdbc包下的Driver类。

Class.forName("com.mysql.jdbc.Driver");

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

//2.创建数据库连接

//数据库的连接地址 -->dbc:mysql:表示mysql数据库的通信协议 -->localhost表示mysql数据库所在服务器的ip地址 -->3306表示数据库访问端口 -->test表示数据库库名

String url = "dbc:mysql://localhost:3306/test";

String username = root;//数据库账号

String password = root;//数据库密码

try {

connection = DriverManager.getConnection(url, username, password);//这里会报异常,所以用try{}catch(){} 处理一下

} catch (SQLException e) {

e.printStackTrace();

}

//3.获取执行sql语句的对象

try {

statement = connection.createStatement();

} catch (SQLException e) {

e.printStackTrace();

}

//4.执行sql语句

try {

resultSet = statement.executeQuery("select * from person");

} catch (SQLException e) {

e.printStackTrace();

}

//5.查看结果集(查询数据库返回的结果)

while (resultSet.next()) {

//获取表中name字段的值

String name = resultSet.getString("name");

System.out.println("name = " + name);

//获取表中age字段的值

String str = resultSet.getString("age");

int age = Integer.parseInt(str);

System.out.println("age = " + age);

}

//6.关闭-->结果集对象-->执行sql语句对象-->数据库连接对象

if (resultSet!=null) {

resultSet.close();

}

if (statement!=null) {

statement.close();

}

if (connection!=null) {

connection.close();

}

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。