日期:2014-05-16 浏览次数:20425 次
?向MySQL插入记录有两种,一种是全部插入,另一种是有选择地插入,其实都很简单,就是sql语句以及stmt.executeUpdate(sql)的运用,下面先讲全部插入的例子。 ? import java.sql.*; ? 这个例子是先插入,后查询。这里要注意的是,当要插入的记录中的某些敏感的列的值与相对应的表中的某个记录的值相同时,运行这个程序时,MyEclipse会抛出异常,提示错误,不要以为是代码错误,这时就要查检将要插入的记录敏感项(比如说:姓名,学号是不能相同的吧)与表中的相对应的值是否有冲突,如果没有,那才是代码错误所致。 ? 第二种是有选择的插入,看例子: ? import java.sql.*; ? 其实这里主要是要学习
public class Mysqls {
??? public static void main(String[] args)
??? {
??? ??? String driver="com.mysql.jdbc.Driver";
??? ??? String url="jdbc:mysql://localhost:3306/mytext";
??? ??? String user="root";
??? ??? String pword="mysql";
??? ??? try{
??? ??? ??? Class.forName(driver);
??? ??? ??? Connection conn=DriverManager.getConnection(url,user,pword);
??? ??? ??? Statement stmt=conn.createStatement();
??? ??? ????String sql="insert into teacher values(810,'李四','男','1967-09-10','教授','计算机系')";
??? ??? ????stmt.executeUpdate(sql);
??? ??? ??? String sqls="select * from teacher";
??? ??? ??? ResultSet rs=stmt.executeQuery(sqls);
??? ??? ??? while(rs.next()){
??? ??? ??? ????
??? ??? ??? ??? System.out.println(rs.getString(1)+rs.getString(2)+rs.getString(3)+rs.getString(4)+rs.getString(5)+rs.getString(6));
??? ??? ??? }
??? ??? ??? rs.close();
??? ??? ??? stmt.close();
??? ??? ??? conn.close();
??? ??? }
??? ??? catch(Exception e){
??? ??? ??? e.printStackTrace();
??? ??? }
??? }
}
public class Mysqls {
??? public static void main(String[] args)
??? {
??? ??? String driver="com.mysql.jdbc.Driver";
??? ??? String url="jdbc:mysql://localhost:3306/mytext";
??? ??? String user="root";
??? ??? String pword="mysql";
??? ??? try{
??? ??? ??? Class.forName(driver);
??? ??? ??? Connection conn=DriverManager.getConnection(url,user,pword);
??? ??? ??? Statement stmt=conn.createStatement();localhost:3306/mytext";
??? ??? String user="root";
??? ??? String pword="mysql";
??? ??? try{
??? ??? ??? Class.forName(driver);
??? ??? ??? Connection conn=DriverManager.getConnection(url,user,pword);
??? ??? ??? Statement stmt=conn.createStatement();
??? ??? ????String sql="insert into teacher(Tno,Sn,Sex) values(810,'李四','男',)";
??? ??? ????stmt.executeUpdate(sql);
??? ??? ??? String sqls="select * from teacher";
??? ??? ??? ResultSet rs=stmt.executeQuery(sqls);
??? ??? ??? while(rs.next()){
??? ??? ??? ????
??? ??? ??? ??? System.out.println(rs.getString(1)+rs.getString(2)+rs.getString(3)+rs.getString(4)+rs.getString(5)+rs.getString(6));
??? ??? ??? }
??? ??? ??? rs.close();
??? ??? ??? stmt.close();
??? ??? ??? conn.close();
??? ??? }
??? ??? catch(Exception e){
??? ??? ??? e.printStackTrace();
??? ??? }
??? }
}