代码:
package com.yikuan.jdbc.dml;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;public class InsertClass { public static void main(String[] args) { Connection conn = null; Statement cs = null; try { //1.加载注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2.连接数据库 String url = "jdbc:mysql://localhost:3306/jdbc_db"; /*远程的写IP地址*/ String user = "root"; String password = "789789"; conn = DriverManager.getConnection(url, user, password); //3.创建sql语句 String sql = "insert into stu values (1,'zhangsan',20)"; cs = conn.createStatement(); //4.执行sql int row = cs.executeUpdate(sql); System.out.println(row); } catch (Exception e) { e.printStackTrace(); } finally { //5.释放资源 if(cs != null){ try { cs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }}
实验结果: