数据库连接问题

来源:互联网 发布:网络枪战手游排行榜 编辑:程序博客网 时间:2024/05/18 14:45

package com.castit.it;

import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Date;

public class TestJDBC2 {

/*** @param args*/ public static void main(String[] args) {  if(args.length != 4) {   System.out.println("格式错误!");   System.exit(-1);  }

  int id = 0;  try {   id = Integer.parseInt(args[0]);  } catch (NumberFormatException e1) {   System.out.println("格式错误!");   System.exit(-1);  }

  String typeName = args[1];  int days = Integer.parseInt(args[2]);  float fk = Float.parseFloat(args[3]);  //ResultSet rs = null;  PreparedStatement stmt = null;  Connection conn = null;  try {   Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");   conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_library","sa","");   stmt = conn.prepareStatement("insert into tb_bookType  values(?,?,?,?)");   //rs = stmt.executeQuery("select * from tb_bookInfo");   /*while(rs.next()) {   System.out.println(rs.getString("bookname"));   //System.out.println(rs.getInt("price"));   }*/   stmt.setInt(1, id);   stmt.setString(2,typeName);   stmt.setInt(3,days);   stmt.setFloat(4,fk);   stmt.executeUpdate();  } catch (ClassNotFoundException e) {  // TODO Auto-generated catch block   e.printStackTrace();  } catch (SQLException e) {   // TODO Auto-generated catch block   e.printStackTrace();  }finally {   try {    /*if(rs != null) {     rs.close();    }*/    if(stmt != null) {     stmt.close();    }     if(conn != null) {      conn.close();     }   } catch (SQLException e) {    // TODO Auto-generated catch block    e.printStackTrace();   }  }

 }

 

}

 

此时会提示这样的错误“仅当使用了列的列表,并且 IDENTITY_INSERT 为 ON 时,才能在表 'tb_bookType' 中为标识列指定显式值。”所以应将stmt = conn.prepareStatement("insert into tb_bookType values(?,?,?,?)"); 改为 stmt = conn.prepareStatement("insert into tb_bookType(id,typeName,days,fk) values(?,?,?,?)"); 此时有提示错误 “当 IDENTITY_INSERT 设置为 OFF 时,不能向表 'tb_bookType' 中的标识列插入显式值。” 故还应改为 stmt = conn.prepareStatement("set identity_insert tb_bookType ON insert into tb_bookType(id,typeName,days,fk) values(?,?,?,?)"); 此时插入数据正常

原创粉丝点击