目录结构:
mysql目录结构:
最初的student表:
代码实现:
Dbutil:
package util;
import java.sql.*;
public class Dbutil {
static{
try{
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
Connection connection = null;
try {
//2.建立连接
//url的格式:主协议:子协议:名称
String url = "jdbc:mysql://127.0.0.1:3306/mysql_test?useUnicode=true&characterEncoding=utf8";
connection = DriverManager.getConnection(url,"root","13474501003");
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return connection;
}
public static void closeConnection(Connection connection){
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void closeStatement(PreparedStatement preparedStatement){
if (preparedStatement != null){
try {
preparedStatement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
Test1:
package demo2;
import util.Dbutil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("请输入要修改的学号:");
int sno = in.nextInt();
System.out.println("请输入新的名字:");
String name = in.next();
System.out.println("请输入新地址:");
String addr = in.next();
System.out.println("请输入新年龄:");
int age = in.nextInt();
//
Connection connection = null;
PreparedStatement preparedStatement = null;
//
connection = Dbutil.getConnection();
try {
String sql = "UPDATE student SET sname=?,addr=?,age=? WHERE sno=?";
preparedStatement = connection.prepareStatement(sql);
//设置参数
preparedStatement.setString(1,name);
preparedStatement.setString(2,addr);
preparedStatement.setInt(3,age);
preparedStatement.setInt(4,sno);
//
int n = preparedStatement.executeUpdate();
//
if (n > 0){
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
Dbutil.closeStatement(preparedStatement);
Dbutil.closeConnection(connection);
}
}
}
结果:
查询student表: