先上執行個體吧,免得你看了鬱悶!
執行個體:
JAVA如何插入MySql的datetime類型
Date date = new Date();
Timestamp timeStamp = new Timestamp(date.getTime());
clientinfo.setClientinfoAddtime(timeStamp);
這樣放入資料庫的就是“yyyy-mm-dd hh:mm:ss”格式的資料
過去我一直都是把時期做為字元類型來處理,汗,最近項目需要比較時間就沒轍了,特意查了下資料才明白java可以直接插入日期型的資料,孤陋寡聞!
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
public class DataBaseTest {
private Connection conn;
PreparedStatement pStmt=null;
private void test(){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url ="jdbc:mysql://localhost:3306/rhino?user=root&password=&useUnicode=true&characterEncoding=UTF-8";
Connection conn= DriverManager.getConnection(url);
System.out.println("connect to database successfully!");
pStmt=conn.prepareStatement("INSERT INTO RH_ENTRY"+
"(id,allow_comments,category_id,comment_count,content,create_on,name,status)"+
"values(?,?,?,?,?,?,?,?)");
conn.setAutoCommit(false);
java.util.Date date=new java.util.Date();
Timestamp tt=new Timestamp(date.getTime());
pStmt.setInt(1,1);
pStmt.setInt(2,1);
pStmt.setInt(3,1);
pStmt.setInt(4,5);
pStmt.setString(5,"shit!!!!!");
pStmt.setTimestamp(6,tt);
pStmt.setString(7,"jordan");
pStmt.setInt(8,1);
int j=pStmt.executeUpdate();
conn.commit();
if(j!=0)
System.out.println("ok");
}catch(Exception e){
try{
conn.rollback();
}catch(Exception e1){
e1.printStackTrace(System.out);
}
e.printStackTrace();
}finally{
try{
pStmt.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String args[]){
DataBaseTest dt=new DataBaseTest();
dt.test();
}
}
數值型
整型 JDBC
tinyint java.lang.Integer
smallint
mediumint java.lang.Long
int
bigint java.math.BigInteger
單精確度浮點型 JDBC
float java.lang.Float
雙精確度浮點型 JDBC
double java.lang.Double
其他 JDBC
decimal java.math.BigDecimal
字元型 JDBC
char java.lang.String
varchar
tinytext
text
mediumtext
longtext
日期型 JDBC
date java.sql.Date
datetime java.sql.Timestamp
timestamp java.sql.Timestamp
time java.sql.Time
year java.sql.Date
其他
tinyblob 待定
blob
mediumblob
longblob
enum
set
-------------------------------------------------------------------------------------------------------
java.util.Date date = new java.util.Date();
Timestamp timeStamp = new Timestamp(date.getTime());
music.setTime(timeStamp);
-------------------------------------------------------------------------------------------------------
private Date time = null;
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}