Java: jSpinner: Write to Access Database?
please i need some help on my school assignment: i just want to know the code on how to get the value of jspinner and insert in to ms acc开发者_开发知识库ess database.
here is my code to format it as MM/dd/yyyy:
SpinnerDateModel model = new SpinnerDateModel();
model.setCalendarField(Calendar.DAY_OF_MONTH);
jSpinner1.setModel(model);
jSpinner1.setEditor(new JSpinner.DateEditor(jSpinner1, "MM/dd/yyyy"));
and this is how i tried to insert it to my database:
Date value = (Date) jSpinner1.getValue();
String SQLString = "INSERT INTO Table1(Username,Password,Website,DateEncoded)VALUES('"+
text1+"','"+text2+"','"+text3+"',"+value+")";
You need to give an error message for anybody to know what is going on. One potential problem is that you aren't using a Prepared Statement. So if text1, text2, text3 or value contain the character "'", your SQL will be wrong. Also, you don't quote "value".
If this seems like the problem, checkout PreparedStatement:
http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html
The JSpinner.getValue() is returning a Date. You are seeing the default toString() method of a Date. You can get the format you want by:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); sdf.format(jSpinner1.getValue());
You should still look at the section on PreparedStatements. That will make it even easier to work with dates.
When you get the value from the spinner, it isn't giving you the displayed string but the value stored in the SpinnerDateModel
. You need to use a DateFormat, perhaps one with a custom string specified to an instance of SimpleDateFormat, and format the date value into a formatted string. Here are some examples of using date formatting in Java.
精彩评论