目录结构:
mysql:
此时的student表:
代码实现添加:
package demo1; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; public class Test2 { public static void main(String args[]){ Scanner in = new Scanner(System.in); Connection connection = null; Statement statement = null; System.out.println("请输入学号:"); int num = in.nextInt(); System.out.println("请输入姓名:"); String name = in.next(); System.out.println("请输入年龄:"); int age = in.nextInt(); try { //加载驱动 Class.forName("com.mysql.jdbc.Driver"); //建立连接 //url的格式:主协议:自协议:名称 String url = "jdbc:mysql://127.0.0.1/mysql_test?useUnicode=true&characterEncoding=utf8"; connection = DriverManager.getConnection(url,"root","13474501003"); //3.准备sql语句,Statement对象 String sql = "INSERT INTO student(sno,sname,age)VALUES("+num+",'"+name+"',"+age+")"; statement = connection.createStatement(); //4.执行 //适用于DML语句 int n=statement.executeUpdate(sql); //5.处理结果 if(n > 0){ System.out.println("添加成功!"); }else{ System.out.println("添加失败!"); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); }finally { try { if(statement != null) { statement.close(); } if (connection != null){ connection.close(); } }catch (SQLException throwables) { throwables.printStackTrace(); } } } }
执行成功:
在查询数据库student表添加成功: