数据库插入

import java.sql.*;

 
import java.util.Scanner;
 
public class jdbcupdate {
    public static void main(String[]args) {
        final String URL = "jdbc:mysql://localhost:3306/test";
        final String USERNAME = "root";
        final String PWD = "12345";
        Connection connection = null;
        Statement  stmt = null;
        Scanner con=new Scanner(System.in);
        String idnumber;
        String classname;
        String teachername;
        String didian;
         
        //idnumber=con.nextLine();
        classname=con.nextLine();
        teachername=con.nextLine();
        //didian=con.nextLine();
        try {
            // a.导入驱动,加载具体的驱动类
            Class.forName("com.mysql.jdbc.Driver");// 加载具体的驱动类
            // b.与数据库建立连接
            connection = DriverManager.getConnection(URL, USERNAME, PWD);
            stmt = connection.createStatement();
             
             
            //删除时如果是中文汉字要加单引号,如果是变量的话需要双引号单引号双引号
            String sql = "update student set teacher='"+teachername+"' where classname='"+classname+"'";
            // 执行SQL
            int count = stmt.executeUpdate(sql);
             
             
             
            // d.处理结果
            if (count > 0) { 
                System.out.println("操作成功!");
            }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        catch (SQLException e) {
            e.printStackTrace();
        catch(Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                 if(stmt!=null) stmt.close();// 对象.方法
                 if(connection!=null)connection.close();
            }catch(SQLException e) {
                e.printStackTrace();
            }
        }
    }
 
 
}
posted @ 2021-05-14 01:13  Zwyooo  阅读(77)  评论(0编辑  收藏  举报