接上一篇MySQL数据库与其管理工具Navicat link
1.下载JDBC
可以登录MySQL的官方网站:www.mysql.com,下载JDBC-MySQL数据库驱动(JDBC Driver for MySQL)下载mysql-connector-java-5.1.40.zip后,将该zip文件解压至硬盘,在解压后的目录下的mysql-connector-java-5.1.40-bin.jar文件就是连接MySQL数据库的JDBC-数据库驱动。将该驱动复制到JDK的扩展目录中如:E:\jdk1.8\jre\lib\ext
2.加载JDBC-MySQL数据库驱动
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e){}
3.连接数据库
Connection con = null;
String url = "jdbc:mysql://127.0.0.1/students?useSSL=true&characterEncoding=utf-8";
String user = "root";
String password = "";
try {
con = (Connection) DriverManager.getConnection(url,user,password);//使用getConnection方法建立连接
}
catch(SQLException e) {}
4.进行增删改查
5.全部代码如下
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class Example11_1 {
//和MySQL数据库服务器建立连接前必须保证该MySQL数据库服务器已经启动。
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection con = null;//链接对象
Statement sql,sql1;//sql语句存放的对象
ResultSet rs,rs2;//sql查询结果存放的对象
try {
Class.forName("com.mysql.jdbc.Driver");//加载MySQL驱动
}
catch(Exception e) {}
String url = "jdbc:mysql://127.0.0.1/students?useSSL=true&characterEncoding=utf-8";
String user = "root";
String password = "";
try {
con = (Connection) DriverManager.getConnection(url,user,password);//使用getConnection方法建立连接
}
catch(SQLException e) {}
//增加
String jiLu = "('S202304','蒋三','2000-12-8',56,98),"+"('S202305','冯四','2006-11-8',89,78)";
String sqlStr = "insert into mess value"+jiLu;
//删除
String delStr = "delete from mess where number='S202303'";
//修改
String upStr = "update mess set name = '程七'where number='S202302'";
try {
sql = (Statement) con.createStatement();//让已创建的连接对象con调用createStatement()创建SQL对象。
int del = sql.executeUpdate(delStr);//执行删除
int ok = sql.executeUpdate(sqlStr);//执行增加
int up = sql.executeUpdate(upStr);//执行修改
//顺序查询
rs = sql.executeQuery("SELECT name,mathScore FROM mess");//将查询结果放在一个ResultSet类声明的对象rs中。
// rs = sql.executeQuery("select * from students");
while(rs.next()) {
// String number = rs.getString("number");
String name = rs.getString("name");
// Date date = rs.getDate("birthday");
float mathScore = rs.getFloat("mathScore");
// System.out.printf("%s\t", number);
System.out.printf("%s\t", name);
// System.out.printf("%s\t", date);
System.out.printf("%s\n", mathScore);
}
con.close();//关闭链接
}
catch(SQLException e) {
System.out.println(e);
}
}
}
6.执行完操作后关闭数据库
文章出处登录后可见!
已经登录?立即刷新