Java通过JDBC连接MySQL数据库

时间:2023-02-08 13:05:19

在连接数据库之前当然需要导入连接数据库的驱动包
Java通过JDBC连接MySQL数据库

如何导入驱动包,网上教程有很多,在次不在叙述。

首先来看看数据库内容:

①Book数据库bookinfo表结构:

Java通过JDBC连接MySQL数据库

②Book数据库bookinfo表内容:

Java通过JDBC连接MySQL数据库

以下就是Java通过JDBC连接数据库的语句:

package cn.xuzihui.db;
//导入连接数据库必要的包
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DButil {

private static final String URL = "jdbc:mysql://localhost:3306/Book";
private static final String USER = "root";
private static final String PASSWORD = "123456";

public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver"); //注册JDBC驱动
Connection conn = DriverManager.getConnection(URL,USER,PASSWORD); //打开链接
Statement st = conn.createStatement();
ResultSet books = st.executeQuery("select * from bookinfo"); //执行查询
while(books.next()) {
//通过字段检索
String bookname = books.getString("book_name");
String bookauthor = books.getString("book_author");
String bookabstract = books.getString("book_abstract");
//输出
System.out.println("Name:"+bookname+"<br>");
System.out.println("Author:"+bookauthor+"<br");
System.out.println("Abstract"+bookabstract+"<br>");
System.out.println("============================================");
}
}

}

以上连接数据库代码是简单的连接语句,忽略了必要的异常,语句上并不是很严谨。下面是相对比较严谨的连接数据库代码:

package cn.xuzihui.db;
//可以逐个导入包,或者可以导入java.sql下的所有包
//import java.sql.Connection;
//import java.sql.DriverManager;
//import java.sql.ResultSet;
//import java.sql.Statement;

import java.sql.*;

public class DBUtil {
private static final String URL = "jdbc:mysql://localhost:3306/Book";
private static final String USER = "root";
private static final String PASSWORD = "123456";
public static void main(String[] args) {
Connection conn = null;
Statement st = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, USER, PASSWORD);
st = conn.createStatement();
ResultSet rs = st.executeQuery("select * from bookinfo");
while(rs.next()) {
String bookname = rs.getString("book_name");
String bookauthor = rs.getString("book_author");
String bookabstract = rs.getString("book_abstract");
System.out.println("Name:"+bookname+"<br>");
System.out.println("Author:"+bookauthor+"<br");
System.out.println("Abstract"+bookabstract+"<br>");
}
rs.close();
st.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace(); // 处理 JDBC 错误
} catch (Exception e) {
e.printStackTrace(); // 处理 Class.forName 错误
} finally {
try { // 关闭资源
if(st!=null)
st.close();
} catch (SQLException se2) {}
try {
if(conn!=null)
conn.close();
} catch (SQLException se3) {
se3.printStackTrace();
}
}
System.out.println("GoodBye!");
}
}