(2)删除一条记录 stmt.executeUpdate("delete from test where name='JJ'");
2.JDBC应用向数据库动态插入数据 源码:通过命令行的参数作为插入的数据源,即动态更新数据库数据
import java.sql.*;
*MySQL数据库编程 * 实例(3):JDBC处理DML语句.通过命令行输入需要插入到数据库中的数据*/ public class JDBC_DML2 { public static void main(String[] args) { if(args.length!=3) //输入不正确,非正常退出 { System.out.println( "Parament Error,Please Input Again!"); System.exit(-1); } String nameParam=args[0]; //获取命令行第一个参数 int ageParam=Integer.parseInt(args[1]); //获取命令行第二个参数,并转换为整型 int scoreParam=Integer.parseInt(args[2]);//获取命令行第三个参数,并转换为整型 //0.连接数据库相关参数 String url="jdbc:mysql://localhost:3306/jdbc_test_db"; //数据库URL(资源定位唯一标识符) String DBusername="root"; //数据库用户名 String DBpasswd="111111"; //数据库密码 //1.加载数据库驱动,将Driver注册到DriverManager中 try{ Class.forName("com.mysql.jdbc.Driver"); }catch(ClassNotFoundException e){ e.printStackTrace(); } //2.通过数据库URL连接到数据库 Connection conn=null; Statement stmt=null; try{ conn=DriverManager.getConnection(url, DBusername, DBpasswd); //3.获取Statement对象 stmt=conn.createStatement(); //4.获取命令参数,并调用Statement对象的executeUpdate更新数据库 String sql="insert into test(name,age,score) values('"+nameParam+"',"+ageParam+","+scoreParam+")"; System.out.println(sql);//调试 stmt.executeUpdate(sql); }catch(SQLException e){ e.printStackTrace(); } //5.释放JDBC资源 if(stmt!=null) //关闭声明 { try{ stmt.close(); }catch(SQLException e){ e.printStackTrace(); } } if(conn!=null) //关闭连接 { try{ conn.close(); }catch(SQLException e){ e.printStackTrace(); } } } }
(1)设置命令行参数 右击工程->Run as->Open Run Dialog->Main Class选择"JDBC_DML2"
(2)运行结果
(3)遇到的错误与调试 输入参数运行 Java应用后,出现SQLException异常。我们可以通过打印输入的插入sql语句,发现程序没有获取到命令行传入的参数,另外,vaules拼写错误,找到原因。 修改:sql="insert into test(name,age,score) values('"+nameParam+"',"+ageParam+","+scoreParam+")";即可