简介
利用java的mysql驱动包连接并操作mysql server,访问数据库、创建和查询表、新增和查询表内信息。
- 首先下载并安装MySQL,下载mysql驱动包,并在项目中导入该包。
- 在这个项目中我封装了mysql的连接操作,并在此基础上实现一个简单的学生管理系统。包括显示全部、按id查询、按名字查询、增加学生。
JDBC
- java的mysql驱动包,需要事先导入到项目中。
- 主要操作有初始化数据库连接、执行语句、获取执行结果、释放数据库连接。
初始化数据库连接
- 准备好DB_URL(数据库地址)、USER(用户名)、PASS(密码)等字段,使用DriverManager.getConnection(DB_URL, USER, PASS)来启动连接
- metaData=conn.getMetaData()获取表数据以判断所需表是否存在
- stmt=conn.createStatement()创建一个statement对象,以执行语句和返回结果
- 如不存在指定的表,则创建一个
查询
拼接好用于查询的字符串query,调用rs=stmt.executeQuery(query),执行该语句并获取执行结果。 int id= rs.getInt(“id”);String name=rs.getString(“name”) 从该结果集中获取相应字段的信息。
新增
在插入的query字符串中预留’?',创建一个 PreparedStatement,
preparedStatement.setInt(1, id) 设置插入字段的值,
int rowsAffected = preparedStatement.executeUpdate(),执行该query并返回生效的行数。
释放
rs.close();释放结果集
stmt.close();释放状态
conn.close();释放连接
package org.example;
import java.sql.*;
import java.util.Scanner;
public class mysql_conn {
public mysql_conn(){
DB_URL="jdbc:mysql://localhost:3306/lxdb?useSSL=false";
USER="ssss";
PASS="ssss";
conn=null;
stmt=null;
}
public static Connection getConn() throws SQLException {
return DriverManager.getConnection(DB_URL, USER, PASS);
}
public void init(String table) throws SQLException {
conn= DriverManager.getConnection(DB_URL,USER,PASS);
metaData=conn.getMetaData();
this.table =table;
rs=metaData.getTables(null,null,table,null);
stmt=conn.createStatement();
if(!rs.next()){
try{
String query="CREATE TABLE "+table+"(id INT PRIMARY KEY,name VARCHAR(50))";
stmt.executeUpdate(query);
System.out.println("Table createed successfully!");
}catch (SQLException e){
e.printStackTrace();
}
}else{
out("Table already exists");
}
}
public void free() throws SQLException {
out("Free...");
rs.close();
stmt.close();
conn.close();
}
public static void inputQuery(String query) throws SQLException {
stmt.execute(query);
}
public static void findById(int id) throws SQLException {
String query="SELECT * FROM "+table+" WHERE ID= "+id+" ;";
rs=stmt.executeQuery(query);
}
public static void findByName(String name)throws SQLException{
String query="SELECT * FROM "+table+" WHERE NAME= '"+name+"' ;";
rs=stmt.executeQuery(query);
}
public static void Insert(int id, String name){
String insertSQL = "INSERT INTO "+table+" (id, name) VALUES (?, ?)";
try (Connection connection = getConn();
PreparedStatement preparedStatement = connection.prepareStatement(insertSQL)) {
// 设置要插入的数据
preparedStatement.setInt(1, id);
preparedStatement.setString(2, name);
// 执行插入操作
int rowsAffected = preparedStatement.executeUpdate();
System.out.println("Inserted " + rowsAffected + " row(s) into the table.");
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void showByRs() throws SQLException {
while (rs.next()){
int id= rs.getInt("id");
String name=rs.getString("name");
System.out.println("ID: "+id+" name: "+name);
}
}
public static void show() throws SQLException {
String query="SELECT * FROM "+table+" ;";
rs=stmt.executeQuery(query);
showByRs();
}
public static void menu() throws SQLException {
while (true){
out("1.show all");
out("2.find by id");
out("3.find by name");
out("4.add");
out("5.quit");
int opt=0;
Scanner sc=new Scanner(System.in);
opt=sc.nextInt();
switch (opt){
case 1:
show();
break;
case 2:
out("id: ");
int id=sc.nextInt();
findById(id);
showByRs();
break;
case 3:
out("name: ");
String name=sc.next();
findByName(name);
showByRs();
break;
case 4:
out("id : ");
int i=sc.nextInt();
out("name : ");
String nam=sc.next();
Insert(i,nam);
show();
break;
case 5:
out("quit");
return;
default:
out("wrong");
}
}
}
public static void out(String str){
System.out.println(str);
}
public static String JDBC_DRIVER;
public static String DB_URL;
public static String USER;
public static String PASS;
public static Connection conn;
public static Statement stmt;
public static DatabaseMetaData metaData;
public static ResultSet rs;
public static String table;
public static void main(String args[]) {
mysql_conn mc=new mysql_conn();
try {
mc.init("stu");
menu();
}catch (SQLException e){
e.printStackTrace();
}finally {
try{
mc.free();
}catch (SQLException e){
e.printStackTrace();
}
}
}
}