欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mysql数据库修改添加Date格式列的方法

程序员文章站 2024-03-01 21:55:46
import java.sql.*; import java.text.dateformat; //数据库的查询 public class selecttab...
import java.sql.*;
import java.text.dateformat;
//数据库的查询
public class selecttable {

    string dbdriver="com.mysql.jdbc.driver";  
     string dburl="jdbc:mysql://localhost:3306/sss";//根据实际情况变化 
     string username="root"; 
     string password="123"; 
     public connection getconn() 
     { 
       connection conn=null; 
       try 
       { 
         class.forname(dbdriver); 
       } 
       catch (classnotfoundexception e) 
       { 
         e.printstacktrace(); 
       } 
       try 
       { 
         conn = drivermanager.getconnection(dburl,username,password);//注意是三个参数 
       } 
       catch (sqlexception e) 
       { 
         e.printstacktrace(); 
       } 
       return conn; 
     } 
 
public void select(){
connection conn = getconn();
try{
 statement stmt = conn.createstatement(); //创建statement对象
        system.out.println("成功连接到数据库!");
        string sql = "select * from jdbc";  //要执行的sql
        resultset rs = stmt.executequery(sql);//创建数据对象


        system.out.println("id"+"\t"+"name"+"\t"+"brithday");
        while (rs.next()){          
        system.out.print(rs.getint(1) + "\t");
          system.out.print(rs.getstring(2) + "\t");
          system.out.print(rs.getdate(3) + "\t");
          system.out.println();
        }
}catch(exception e){
e.printstacktrace();
}
        
      
      } 
public void insert(){
connection conn = getconn();
try{
statement stmt = conn.createstatement();
system.out.println("成功连接到数据库!");
string sql = "insert into jdbc (id,name,birthday) values(?,?,?)";
preparedstatement pst =conn.preparestatement(sql);
dateformat df = dateformat.getdateinstance();
 
java.util.date dd = df.parse("2000-12-12");//将yyyy-mm-dd格式的时间转换为date
long t = dd.gettime();
java.sql.date date = new java.sql.date(t);
 

pst.setint(1, 5);
pst.setstring(2, "limazhi");
pst.setdate(3, date);
pst.executeupdate();
select();
}catch(exception e){
e.printstacktrace();
}
 
}
public static void main(string args[]){
selecttable st = new selecttable();
st.insert();
}
     
}