Inserting data into MY SQL database - java

I am trying to insert values retrieved from dictionary into Database but unable to do so,
my insert statement is as follows,
String command="INSERT INTO TABLE1(elog_r)VALUES(#rV where id=#value);";
where value of rV is
rV=dict.get("VOLTAGE-VR");
In ASP.NET we can write as
command.Parameters.AddWithValue("#rV", rV);
I want the solution for the same in JAVA.

This is the sample from mykong website, which you can give you some hint about using the java JDBC to insert data in a table:
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "mkyong");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
// execute insert SQL stetement
preparedStatement .executeUpdate();
You can follow the complete tutorial here:
http://www.mkyong.com/jdbc/jdbc-preparestatement-example-insert-a-record/

Related

Java String insertion to MySQL field of type MEDIUMTEXT

I'm taking a string and inserting it into a mySQL database field of type MEDIUMTEXT. When I print it out, there is a bunch of '-' characters and whitespace surrounding a slightly corrupted version of my original text. Am I doing this wrong?
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tripDB?characterEncoding=utf8","root","pass");
Statement stmt = con.createStatement();
query = "insert into trip (name, date, details) values (?, ?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setString(1, name); //Inserts correctly (varchar)
preparedStmt.setString(2, date); //Correct (varchar)
preparedStmt.setString(3, details); //Corrupted (MEDIUMTEXT)
preparedStmt.execute();
con.close();

How to get sequence.nextval from SQL in JDBC?

I have 5 tables where I use the same sequence's next value. The problem is, the subsequent tables gets a bigger value than the previous ones.
My code is like this:
String sql = "INSERT INTO table1(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "bar");
ps.executeUpdate();
sql = "INSERT INTO table2(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "tar");
ps.executeUpdate();
sql = "INSERT INTO table3(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "par");
ps.executeUpdate();
sql = "INSERT INTO table4(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "car");
ps.executeUpdate();
sql = "INSERT INTO table5(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "rar");
ps.executeUpdate();
My sequence is like this:
CREATE SEQUENCE "ID_SEQ" MINVALUE 1 MAXVALUE 9999999999 INCREMENT BY 1 START WITH 10 CACHE 20 NOORDER NOCYCLE ;
Now when I look at my tables, table1's ID is 10, but table2's ID is 11 and table3's ID is 12..... I want all the tables' IDs to be same. What should I do?
Thank you in advance.
edit: Had to include more tables than 2 to have more general question
Actually I found the answer online. I need to do this:
String sql = "select ID_SEQ.nextval from DUAL";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if(rs.next())
int nextID_from_seq = rs.getInt(1);
And when I insert this value to database, I type this:
String sql2 = "INSERT INTO table1(id, name) VALUES (?, ?)";
ps.setInt(1, nextID_from_seq);
ps.setString(2, "tar");
ps.executeUpdate();
sql2 = "INSERT INTO table2(id, name) VALUES (?, ?)";
ps.setInt(1, nextID_from_seq);
ps.setString(2, "par");
ps.executeUpdate();
...
...
The first string sql is "select ID_SEQ.nextval from DUAL." That "DUAL" in the end is not table name or anything. It's just one of the given or provided functionality by oracle. I can get any sequence's nextval by using it.
You can use id_seq.currval for the second table. It will reuse the same id.
sql = "INSERT INTO table2(id, name) VALUES (id_seq.currval, ?)";

Delete query with integer variable not working

My database contains one column having data type as Integer. I want to delete record using that column value but i'm getting an error.
Here is my code
int id=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter ID to serach"));
//....code
st.executeUpdate("delete from Table where ID='"+id+"'");
I'm getting following error:
Data type mismatch in criteria expression.
you pass a VARCHAR value in your query:
delete from Table where ID='"+id+"'"
just remove the ' and try it again.
I bet your ID is of type NUMBER.
Furthermore I suggest you to use an PreparedStatement to add the Integer value:
delete from Table where ID=?
Otherwise you could have some security problems.
Simple change to :
st.executeUpdate("delete from Table where ID = "+id);
OR
SQLiteDatabase _db = null;
DataBaseHelper _dbHelper = new DataBaseHelper(_context, name, null, 1);
_db = _dbHelper.getWritableDatabase();
_db.delete(TABLE, _ID + "=?", new String[]{id});
So you are inserting integer and not character.Thus no need of single quote around value you are inserting ie int value.It should be
st.executeUpdate("DELETE FROM Table WHERE ID="+id);
It is good practice to have main key words/clauses in Uppercase.And one more, always try to use PreparedStatement rather simple Statement.
EDIT
PreparedStatement Example to insert into database
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "mkyong");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
// execute insert SQL stetement
preparedStatement .executeUpdate();

Insert using PreparedStatement. How do I auto-increment the ID?

I have a PreparedStatement such as:
PreparedStatement preparedStatement = connect.prepareStatement("INSERT into employee (id, time, name" + "(?,?,?)",Statement.RETURN_GENERATED_KEYS);
ResultSet tableKeys = preparedStatement.getGeneratedKeys();
preparedStatement.executeUpdate();
tableKeys.next();
int autoGeneratedID = tableKeys.getInt(1);
preparedStatement.setInt(1,autoGeneratedID);
preparedStatement.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime()));
preparedStatement.setString(3, "Test");
preparedStatement.executeUpdate();
As you can see, the Employee table has an auto-incremented ID. I need to basically add it in automatically using preparedStatement as well. Can someone tell me where I am going wrong and correct me? Right now it just gives me an error related to Statement.
Leave the column out of the INSERT statement entirely. It will be generated by the database engine. Your query should be:
INSERT INTO employee (time, name)
VALUES (?, ?)
Secondly, you have to perform the insert first, then get the keys out of the result.
I believe your code should be:
PreparedStatement preparedStatement =
connect.prepareStatement("INSERT into employee (time, name) VALUES (?,?)",
Statement.RETURN_GENERATED_KEYS);
preparedStatement.setTimestamp(1,
new java.sql.Timestamp(new java.util.Date().getTime()));
preparedStatement.setString(2, "Test");
preparedStatement.executeUpdate();
ResultSet tableKeys = preparedStatement.getGeneratedKeys();
tableKeys.next();
int autoGeneratedID = tableKeys.getInt(1);
Note this example does not check the success of the executed statement or the existence of returned keys.
You should perform some modification(define default statement) to prepared statement string like this:
"INSERT into employee VALUES(default,?,?)"
That modification is because of occurring this problem : Column count doesn't match value count at row 1 JAVA mysql
After that you're code is something like below:
PreparedStatement preparedStatement =
connect.prepareStatement("INSERT into employee VALUES (default,?,?)", Statement.RETURN_GENERATED_KEYS);
preparedStatement.setTimestamp(1, new java.sql.Timestamp(new java.util.Date().getTime()));
preparedStatement.setString(2, "Test");
preparedStatement.executeUpdate();
ResultSet tableKeys = preparedStatement.getGeneratedKeys();
tableKeys.next();
Thanks to Ic. for his answer.
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","password");
PreparedStatement ps = con.prepareStatement("insert into imgslider(id,cmnt,date1,img,status) values(seq.nextval,?,?,?,?)");
ResultSet rs = null;
String s1 = "I’ve Come and I’m Gone: A Tribute to Istanbul’s Street";
ps.setString(1,s1);
Calendar calendar = Calendar.getInstance();
java.sql.Date dd = new java.sql.Date(calendar.getTime().getTime());
ps.setDate(2,dd);
FileInputStream f1 = new FileInputStream("F:\\java\\slide-9.jpg");
ps.setBinaryStream(3,f1,f1.available());
ps.setInt(4,0);
int i = ps.executeUpdate();
System.out.println(i+" rows affected");
con.close();
}
here is my code for auto-increment column in table by PreparedStatement.

error java.sql.SQLException: Parameter index out of range

I still get error that I don't provide value for 1 parameter and I don't have idea what is wrong.
ps("INSERT INTO slide (presentation_id, duration, position, type) values (?, ?, ?, ?) ").set(this.getId()).set(slide.getDuration()).set(slide.getPosition()).set(slide.getType().ordinal()).update();
In table I only do not provide value for one column for which autoincrement is set.
Everything seems alright for me but please give any advice what might be wrong.
dont include the auto inc fieldin your column list.
ps("INSERT INTO slide (duration, position, type) values (?, ?, ?) ").set(slide.getDuration()).set(slide.getPosition()).set(slide.getType().ordinal()).update();
Try to do something more clean instead of this "train code"
This is an example:
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "mkyong");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
// execute insert SQL stetement
preparedStatement .executeUpdate();
and here is the link to follow: http://www.mkyong.com/jdbc/jdbc-preparestatement-example-insert-a-record/

Categories