If you are used to MySQL then you probably know the MySQL function NOW() which inserts the current date and time in a MySQL query. But if you use JDBC and prepared statements, then you can reconstruct this function with a GregorianCalendar (which is the successor of Date):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public void insertArticle(Article article) throws SQLException { //query = "INSERT INTO articles(title,content,date) VALUES (?,?,NOW())"; query = "INSERT INTO articles(title,content,date) VALUES (?,?,?)"; statement = connection.prepareStatement(query); statement.setString(1, article.getTitle()); statement.setString(2, article.getContent()); statement.setTimestamp(3, new Timestamp(new GregorianCalendar().getTimeInMillis())); logger.info(statement); statement.executeUpdate(); } |
If you have a big MySQL table and you want to insert data only in specific columns, then you can do this with naming the columns in parentheses after the table name:
INSERT INTO `wp_posts`(`post_author`,`post_content`,`post_title`,`post_date`) VALUES (0,'Hello World','Text...',NOW());
This works even without apostrophes:
INSERT INTO wp_posts(post_author,post_content,post_title,post_date) VALUES (0,'Hello World','Text...',NOW());
If you receive an error that is similar to this:
java.sql.SQLException: Value ’0000-00-00 00:00:00′ can not be represented as java.sql.Date
Then you should check your database connection. If your connection url looks like jdbc:mysql://localhost/my_database then you should try jdbc:mysql://localhost/my_database?zeroDateTimeBehavior=convertToNull.
Other options are:
jdbc:mysql://localhost/my_database?zeroDateTimeBehavior=round
jdbc:mysql://localhost/my_database?zeroDateTimeBehavior=exception
The explanation can be found in “handling DATETIME values“.
In the beginning of my study time I’ve programmed a MySQL connection in Java for a music collection. After 2 years now I have made a remake of this code to show how to use the Java Database Connectivity (JDBC). All you need is mysql-connector-java-5.0.8-bin.jar.
I’ve written a small sample for the connection with a WordPress database. …weiterlesen
Beim Zugriff auf eine Datenbank sollte man mit PHP immer auf PDO (PHP Data Objects) zurückgreifen. Durch diese Abstraktionsstufe ist das Datenbank-System später einfacher austauschbar und Prepared Statements lassen sich auch ganz leicht realisieren. Hierzu ein exemplarischer Beispielcode. …weiterlesen
Ich lerne gerade die Programmiersprache Python, um das Webframework Django benutzen zu können. Als Windows-Liebhaber habe ich mich sehr gefreut, dass es mit Instant Django eine Lösung gibt, um ganz einfach und unkompliziert entwickeln zu können.
Leider ist in “Instant Django” keine Schnittstelle für MySQL-Datenbanken enthalten (sondern nur SQLite), weshalb man die MySQL-Unterstützung nachträglich installieren muss. Wie das geht, zeige ich. …weiterlesen

0