5、修改信息
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Scanner; public class Text4 { public static void main(String[] args) throws SQLException { //修改信息 Scanner scanner = new Scanner(System.in); System.out.println("请输入学生的id:"); int id = scanner.nextInt(); System.out.println("请输入修改学生姓名:"); String name = scanner.next(); //1,创建实列 DataSource dataSource = new MysqlDataSource(); ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java122?characterEncoding=utf-8&useSSL=false"); ((MysqlDataSource) dataSource).setUser("root"); ((MysqlDataSource) dataSource).setPassword("180210"); //2,数据库连接 Connection connection = dataSource.getConnection(); //3,拼装SQL String sql = "update text set name = ? where id = ?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1,name); statement.setInt(2,id); //4,执行SQL int set = statement.executeUpdate(); if (set == 1){ System.out.println("修改成功"); }else { System.out.println("修改失败"); } //5,关闭资源 statement.close(); connection.close(); } }
到此这篇关于MySQL五步走JDBC编程全解读的文章就介绍到这了,更多相关MySQL JDBC编程内容请搜索
更多SQL内容来自木庄网络博客