i have this code to insert data into mysql db, when i run on eclipse the following code it doesn't show any errors but no data are inserted into the db.
this is my code.
public static void main (String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/database_spie";
Connection conn = DriverManager.getConnection(url,"root","lecci");
Statement st = conn.createStatement();
st = conn.prepareStatement("INSERT INTO database_spie.notifiche(titolo, destinatario, testo) \r\n" +
"VALUES ('inizio', 'tutti', 'spie per una notte inizia tra 30 minuti');");
conn.close();
System.out.println("closed");
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
First point is you need to use PreparedStatement not Statement.
You have only created connection, created query and then closed connection
PreparedStatement st = conn.prepareStatement("INSERT INTO database_spie.notifiche(titolo, destinatario, testo) \r\n" +
"VALUES ('inizio', 'tutti', 'spie per una notte inizia tra 30 minuti');");
//Before closing connection you need to execute it using following line of code
st.executeUpdate();
conn.close();
You should follow these steps: source (https://alvinalexander.com/java/java-mysql-update-query-example)
Create a Java Connection to our MySQL database.
Create a SQL UPDATE statement, using the Java PreparedStatement syntax.
Set the fields on
our Java PreparedStatement object
Execute a Java PreparedStatement
Close our Java database connection. Catch any exceptions that may
come up during the process
If you are using Statement then you need to do it like below
Statement stmt=con.createStatement();
//pass the query string to it
stmt.executeUpdate("INSERT INTO database_spie.notifiche(titolo, destinatario, testo) \r\n" +
"VALUES ('inizio', 'tutti', 'spie per una notte inizia tra 30 minuti');");
You have not executed the statement, just created it then closed the connection.
there is an execute() method on the PreparedStatement object.
Related
I would like to add a date value from JXDatePicker into my SQL database, however I'm getting this error when running it:
java.sql.sqldataexception: the syntax of the string representation of a datetime value is incorrect
This is my code:
try {
String url = "jdbc:derby://localhost:1527/Members";
String username = "admin1";
String password = "admin1";
Connection con = DriverManager.getConnection(url, username, password);
Statement stmt = con.createStatement();
String query = "INSERT INTO BOOKING(MEMBERID, NAME, CONTACT, "
+ "EMAILADDRESS, RESERVATIONDATE, RESERVATIONTIME) "
+ "VALUES('"+txtMemberID.getText()+"', '"+txtName.getText()+"', "
+ "'"+txtContact.getText()+"', '"+txtEmail.getText()+"', "
+ "'"+comboDate.getDate()+"', '"+comboTime.getSelectedItem()+"')";
stmt.execute(query);
JOptionPane.showMessageDialog(null, "Booking created");
txtMemberID.setText(null);
txtName.setText(null);
txtContact.setText(null);
txtEmail.setText(null);
comboDate.setDate(null);
comboTime.setSelectedItem("00");
}
catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}
The datatype specified for the Date attribute in my database is Date.
Thank you.
Your problem is that you're trying to embed a Date value (or a String representation of one) into the INSERT statement. Instead of concatenating variables into the query literal, you should use parameterized SQL through a PreparedStatement. In addition to protecting your code from SQL injection, parameterized statements are re-usable by the database, which means that the DB doesn't need to parse the SQL before each execution -- this is especially important if you're running a large number of queries in a loop.
Another thing that you should take care of, is closing the resources you've opened. In your example code, the Connection and Statement are left open after they are no longer needed. This is easy to fix using the try-with-resources statement, which was introduced in Java 7. The resources declared within the try clause get automatically closed after the statement is executed.
Putting it all together, here's an example of what the modified code could look like:
String query = "INSERT INTO BOOKING(MEMBERID, NAME, CONTACT, "
+ "EMAILADDRESS, RESERVATIONDATE, RESERVATIONTIME) "
+ "VALUES(?, ?, ?, ?, ?, ?)";
try (Connection con = DriverManager.getConnection(url, username, password);
PreparedStatement ps = con.prepareStatement(query)) {
ps.setString(1, txtMemberID.getText());
ps.setString(2, txtName.getText());
ps.setString(3, txtContact.getText());
ps.setString(4, txtEmail.getText());
ps.setDate(5, new java.sql.Date(comboDate.getDate().getTime()));
ps.setString(6, comboTime.getSelectedItem().toString());
ps.executeUpdate();
JOptionPane.showMessageDialog(null, "Booking created");
/*clear the UI components etc.*/
} catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString(), JOptionPane.ERROR_MESSAGE);
}
hi i have tried this command on my sqlite database but it wont drop/delete my database table,
here my reference
Statement stmt = conn.createStatement();
String sqlCommand = "DROP TABLE 'myTable' ";
System.out.println("output : " + stmt.executeUpdate(sqlCommand));
//Output
output : 0
there are no return error so i still cant figure by myself what is making the code not working.
Code to Drop Table
Connection c = null;
Statement stmt = null;
String sql;
c = openSqlite(c); //method i create to setup sqlite database connection
stmt = c.createStatement();
try{
System.out.println("Deleting table in given database...");
String sqlCommand = "DROP TABLE 'myTable' ";
stmt.executeUpdate(sqlCommand);
System.out.println("Table deleted in given database...");
stmt.close();
c.commit();
c.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}
Thanks to MadProgrammer and other, Actually i miss to put commit statement on my code..
Statement stmt = conn.createStatement();
String sqlCommand = "DROP TABLE IF EXISTS 'myDatabase.myTable' ";
System.out.println("output : " + stmt.executeUpdate(sqlCommand));
stmt.close();
conn.commit(); // commit after execute sql command
//COMMIT TRANSACTION makes all data modifications performed since
//the start of the transaction a permanent part of the database,
conn.close();
I want to execute a query in Java.
I create a connection. Then I want to execute an INSERT statement, when done, the connection is closed but I want to execute some insert statement by a connection and when the loop is finished then closing connection.
What can I do ?
My sample code is :
public NewClass() throws SQLException {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
return;
}
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:orcl1", "test",
"oracle");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
return;
}
if (connection != null) {
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from test.special_columns");
while (rs.next()) {
this.ColName = rs.getNString("column_name");
this.script = "insert into test.alldata (colname) ( select " + ColName + " from test.alldata2 ) " ;
stmt.executeUpdate("" + script);
}
}
else {
System.out.println("Failed to make connection!");
}
}
When the select statement ("SELECT * from test.special_columns") is executed, the loop must be twice, but when (stmt.executeUpdate("" + script)) is executed and done, then closing the connection and return from the class.
Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously.
import java.sql.*;
public class jdbcConn {
public static void main(String[] args) throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","name","pass");
Statement stmt = con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String insertEmp1 = "insert into emp values
(10,'jay','trainee')";
String insertEmp2 = "insert into emp values
(11,'jayes','trainee')";
String insertEmp3 = "insert into emp values
(12,'shail','trainee')";
con.setAutoCommit(false);
stmt.addBatch(insertEmp1);
stmt.addBatch(insertEmp2);
stmt.addBatch(insertEmp3);
ResultSet rs = stmt.executeQuery("select * from emp");
rs.last();
System.out.println("rows before batch execution= "
+ rs.getRow());
stmt.executeBatch();
con.commit();
System.out.println("Batch executed");
rs = stmt.executeQuery("select * from emp");
rs.last();
System.out.println("rows after batch execution= "
+ rs.getRow());
}
}
Result:
The above code sample will produce the following result.The result may vary.
rows before batch execution= 6
Batch executed
rows after batch execution= = 9
Source: Execute multiple SQL statements
In the abscence of the schema or the data contained in each table I'm going to make the following assumptions:
The table special_columns could look like this:
column_name
-----------
column_1
column_2
column_3
The table alldata2 could look like this:
column_1 | column_2 | column_3
---------------------------------
value_1_1 | value_2_1 | value_3_1
value_1_2 | value_2_2 | value_3_2
The table alldata should, after inserts have, happened look like this:
colname
---------
value_1_1
value_1_2
value_2_1
value_2_2
value_3_1
value_3_2
Given these assumptions you can copy the data like this:
try (
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl1", "test", "oracle")
)
{
StringBuilder columnNames = new StringBuilder();
try (
Statement select = connection.createStatement();
ResultSet specialColumns = select.executeQuery("SELECT column_name FROM special_columns");
Statement insert = connection.createStatement()
)
{
while (specialColumns.next())
{
int batchSize = 0;
insert.addBatch("INSERT INTO alldata(colname) SELECT " + specialColumns.getString(1) + " FROM alldata2");
if (batchSize >= MAX_BATCH_SIZE)
{
insert.executeBatch();
batchSize = 0;
}
}
insert.executeBatch();
}
A couple of things to note:
MAX_BATCH_SIZE should be set to a value based on your database configuration and the data being inserted.
this code is using the Java 7 try-with-resources feature to ensure the database resources are released when they're finished with.
you haven't needed to do a Class.forName since the service provider mechanism was introduced as detailed in the JavaDoc for DriverManager.
There are two problems in your code. First you use the same Statement object (stmt) to execute the select query, and the insert. In JDBC, executing a statement will close the ResultSet of the previous execute on the same object.
In your code, you loop over the ResultSet and execute an insert for each row. However executing that statement will close the ResultSet and therefor on the next iteration the call to next() will throw an SQLException as the ResultSet is closed.
The solution is to use two Statement objects: one for the select and one for the insert. This will however not always work by default, as you are working in autoCommit (this is the default), and with auto commit, the execution of any statement will commit any previous transactions (which usually also closes the ResultSet, although this may differ between databases and JDBC drivers). You either need to disable auto commit, or create the result set as holdable over commit (unless that already is the default of your JDBC driver).
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con1=DriverManager.getConnection("jdbc:odbc:MyDatabase");
st1=con1.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
System.out.println("Connect database in BallMoves1.java .......");
/*the below line giving error*/
rs1 = st1.executeQuery("insert into highscore" + " (score) " + "values('"+score+"')");
System.out.println("Score is inserted..");
System.out.println("Score......."+score);
}catch(Exception e){ e.printStackTrace();}
/*highscore is table and attributes of table are (sid,score).
the resulting error is:
Connect database in BallMoves1.java .......
java.sql.SQLException: No ResultSet was produced
at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(JdbcOdbcStatement.java:258)
at BallMoves1.move(BallMoves1.java:378)
at BallMoves1.run(BallMoves1.java:223)
at java.lang.Thread.run(Thread.java:744)*/
You're calling executeQuery on something that isn't a query. But instead of calling execute with the same SQL, you should use a PreparedStatement:
String sql = "insert into highscore (score) values (?)";
try (Connection conn = DriverManager.getConnection("jdbc:odbc:MyDatabase");
PreparedStatement statement = conn.prepareStatement(sql)) {
statement.setInt(1, score);
statement.executeUpdate();
conn.commit();
}
Always use parameterized SQL, instead of plugging the values directly into the SQL - that protects you from SQL injection attacks, conversion errors, and hard-to-read code.
Use a try-with-resources statement (as I have) to automatically close the statement and connection at the end of the block.
Hi I've been trying to insert a string into a sqlite database through java. but the string parameter I'm passing in the values sql statement has quotation marks in it as content. I'm thinking that is the error I'm getting why it isn't inserting into the database. is there a way to bypass the quotation marks in the insert statement. thank you.
this is the code:
public void addNote(String topicadd, String contentadd) throws Exception
{
try
{
getConnection();
statement = conn.createStatement();
statement.executeUpdate("insert into tbl_notes (notes_topic, notes_content) values ('" + topicadd + "', '" + contentadd +"')");
System.out.println("inserted note");
}
catch (Exception m)
{`enter code here`
System.out.println("error insert topic");
System.out.println(m.getMessage());
}
}
this is the parameter kind of long... this is all in contentadd
import java.sql.*;
Resultset rset = null; (this has no new ResultSet() initialization)
Connection conn = null; (this has no new initialization too...)
Statement statement = null; (this has now new initialization)
always.....
try
{
}
catch (Exception e) <- can switch e for any other alphabet
{
e.getMessage();
System.out.println("error this module"); <- personal practice
throw e;
}
- getting connection
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:m.db");
*** this is sqlite connection format 'm.db' is the database name
establish connection first..
statement syntax follows:
statement = conn.createStatement();
rset = statement.executeQuery("select * from tbl_notes");
- executeQuery is used for SELECT sql statements
rset = statement.executeUpdate("insert into tbl_notes (ID, status) values
('100', 'status here');
the whole text is in string contentadd, I'm making a short note-taking program... Well, it doesn't execute the insert statement... error somewhere near (word from text) on command prompt... I'm using sqlite... Please let me know if you need more detail. thank you again.
Use a PreparedStatement to insert values containing special characters:
getConnection();
PreparedStatement statement = conn.prepareStatement("insert into tbl_notes (notes_topic, notes_content) values (?, ?)");
statement.setString(1, topicadd);
statement.setString(2, contentadd);
statement.executeUpdate();
As you see you can use parameters with a PreparedStatement which can contain also quotation marks.
Also you get some protection against SQL injection because the Strings given to a PreparedStatement are escaped accordingly.