2 qq 31626965 qq_31626965 于 2016.09.22 21:37 提问

关于java中preparedStatement的一个小问题(很简单!跪求!)

goods表字段为number(文本,主键) name(文本) madeTime(日期) price(数字,双精度)

AddRecord.java

 import java.sql.*;
public class AddRecord {
   String databaseName="";          //数据库名
   String tableName="";                 //表名
   String number="",                //商品号 
          name="",                  //名称
          madeTime;                 //生产日期
   double price;                        //价格
   public AddRecord() {
      try{ Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
      }
      catch(ClassNotFoundException e) {
         System.out.print(e);
      } 
    }
   public void setDatabaseName(String s) {
      databaseName=s.trim();
   }
   public void setTableName(String s) {
      tableName=s.trim();
   }
    public void setNumber(String s) {
       number=s.trim();
    }
    public void setName(String s) {
       name=s.trim();
    }
    public void setPrice(double n) {
       price=n;
    }
    public void setMadeTime(String b) {
        madeTime=b;
    }
    public String addRecord() {
       String str="";
       Connection con;
       PreparedStatement sql;   //预处理语句
       try { String uri="jdbc:derby:"+databaseName+";create=true"; 
             con=DriverManager.getConnection(uri);
             String insertCondition="INSERT INTO "+tableName+" VALUES (?,?,?,?)";
             sql=con.prepareStatement(insertCondition);
             if(number.length()>0) {
               sql.setString(1,number);
               sql.setString(2,name);
               sql.setString(3,madeTime);
               sql.setDouble(4,price);
               int m=sql.executeUpdate();
               if(m!=0) 
                   str="对表中添加"+m+"条记录成功";
               else 
                  str="添加记录失败";
            }
            else {
               str="必须要有雇员号";
            }
            con.close();
       }
       catch(SQLException e) { 
            str="没有提供添加的数据或"+e;
       }
       return str;
    }
}  

Test.java

 public class Example11_10 {
   public static void main(String args[]) {
     AddRecord insertRecord=new AddRecord();
     String database="shop";
     String tableName="goods";
     insertRecord.setDatabaseName(database);
     insertRecord.setTableName(tableName);
     insertRecord.setNumber("D001");
     insertRecord.setName("联想电脑");
     insertRecord.setMadeTime("2015-12-10");
     insertRecord.setPrice(5600);
     String backMess=insertRecord.addRecord();
     System.out.println(backMess);
   }
}

为什么prepareStatement方法中insert语句的in参数,在set第三个日期时是setString而不是setDate,我知道madeTime定义是String类型,但是为什么可以用setString来对应日期类型字段?

5个回答

zhuiyisinian
zhuiyisinian   2016.09.22 22:22

会自动转换的,在sql语句内

hokingshuojin
hokingshuojin   2016.09.22 22:34

即使直接用SQL语句操作数据库时,输入日期类型也是字符串类型,只要是oracle数据库规定的日期格式就能正确输入。但是个人认为还是添加输入验证比较好

a541995149
a541995149   2016.09.22 23:28

Using java.sql.Date

If your table has a column of type DATE:

The method java.sql.Date.valueOf(java.lang.String) received a string representing a date in the format yyyy-[m]m-[d]d. e.g.:
ps.setDate(2, java.sql.Date.valueOf("2013-09-04");

Suppose you have a variable endDate of type java.util.Date, you make the conversion thus:
ps.setDate(2, new java.sql.Date(endDate.getTime());

If you want to insert the current date:
ps.setDate(2, new java.sql.Date(System.currentTimeMillis()));

// Since Java 8
ps.setDate(2, java.sql.Date.valueOf(java.time.LocalDate.now()));

Using java.sql.Timestamp

If your table has a column of type TIMESTAMP or DATETIME:

The method java.sql.Timestamp.valueOf(java.lang.String) received a string representing a date in the format yyyy-[m]m-[d]d hh:mm:ss[.f...]. e.g.:ps.setTimestamp(2, java.sql.Timestamp.valueOf("2013-09-04 13:30:00");

Suppose you have a variable endDate of type java.util.Date, you make the conversion thus:
ps.setTimestamp(2, new java.sql.Timestamp(endDate.getTime()));

If you require the current timestamp:
ps.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis()));

// Since Java 8
ps.setTimestamp(2, java.sql.Timestamp.from(java.time.Instant.now()));
ps.setTimestamp(2, java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
参考:

a541995149
a541995149   2016.09.22 23:28
Marksinoberg
Marksinoberg   Ds   Rxr 2016.09.23 08:51
 直接用SQL语句操作数据库时,输入日期类型也是字符串类型
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!