I need help on INSERT statements using JDBC - java

I need to use an INSERT statement, and 2 of the records in this statement are fields which are calculated in the program, and need to be added to the database.
System.out.println("Executing....");
stmt = conn.createStatement();
String sql;
sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01', PKmod, PKexpo)";
stmt.executeUpdate(sql);
'PKmod' and 'PKexpo' are BigInteger fields whose value is calculated in the java program, how can I add these values to the database?
Thanks for any help! :)

Please do not insert sqls this way. Use prepared statement. Change your sql to use "?" markers instead of concatenating values.

It depends on the DBMS. For mysql perhaps BIGINT should suffice?
http://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html

You need to concatenate the string!!!!
So do as follows:
sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01',"+ PKmod+", "+PKexpo+")";

System.out.println("Executing....");
stmt = conn.createStatement();
String sql;
sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01', "
+ PKmod
+ ", "
+ PKexpo
+ ")";
stmt.executeUpdate(sql);

// First Check That PKmod & PKexpo values are not Zero Or Null.
System.out.println("Executing....");
String sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01'," + PKmod + "," + PKexpo +")";
PreparedStatement pStmt = null;
pStmt = con.prepareStatement(sql);
pStmt.executeUpdate();
closePreparedStatement(pStmt);

Related

insert json data into postgres database using java program

I'm looking for help to insert json data into postgres table using java program. I have tried with following code but cannot find any data is inserted in to the table. I have very little experience in programming. Can some one help me to modify my program to make it work?
here is my code.
enter code here stmt = c.createStatement();
String sql = "CREATE TABLE jason " +
"(ID INT NOT NULL," +
" NAME json NOT NULL)";
stmt.executeUpdate(sql); //updates the table
//json data----------------
String[] MESSAGE = {"{\"customer_name\": \"John\", \"items\": { \"description\": \"milk\", \"quantity\": 4 } }"};
sql = "INSERT INTO jason (ID,NAME) "
+ "VALUES (1,::MESSAGE );";
stmt.executeUpdate(sql);
You have problem with syntax here, please read this instruction: https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html
It's should be:
PreparedStatement pstmt = con.prepareStatement("INSERT INTO jason (ID,NAME) VALUES (1, ?1);");
pstmt.setString(1, yourJsonString)
To use parameters in a statement, you need to use a prepared statement:
java.sql.PreparedStatement stmt = conn.prepareStatement("INSERT INTO jason (ID,NAME) VALUES (1,?)" );
stmt.setString(1, "{\"customer_name\": \"John\", \"items\": { \"description\": \"milk\", \"quantity\": 4 } }");
stmt.executeUpdate();

unable to compare screen values with sql table value

I am trying to compare the screen values input against the value stored in DB. Currently i am trying this code:
cell = sheet.getRow(i).getCell(2);
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection ("jdbc:mysql://madison-dev.czr6vej2htnn.us-east-1.rds.amazonaws.com:3306/madisondb","madisonadmin","t4xuw94$");// + "databasename=madison-dev.czr6vej2htnn.us-east-1.rds.amazonaws.com";
Statement st = con.createStatement();
ResultSet Rs = st.executeQuery("select name, zipcode, state, city, street from business_master where user_id =(\r\n" +
"select id\r\n" +
"from user_master\r\n" +
"where email = 'cell.getStringCellValue()') \r\n");
while (Rs.next()) {
// System.out.println(Rs.getString(1) + " " + Rs.getString(2) + " " + Rs.getString(3) + " "
// + Rs.getString(4) + " " + Rs.getString(5));
System.out.println(Rs.getString(0));
}
The screen is not showing any values.. and when i am trying to print System.out.println(Rs.getString(3)) outside of the loop it gives me an error
java.sql.SQLException: Illegal operation on empty result set.
You are trying to find all the rows where the email address is literally the text 'cell.getStringCellValue()' rather than the value returned by that method.
Whilst you code assemble your query string, that lays you open to SQL injection attacks. Use a prepared statement instead
PreparedStatement st = con.prepareStatement(
"select name, zipcode, state, city, street from business_master where user_id =(" +
"select id " +
"from user_master " +
"where email = ?)");
st.setString(1, cell.getStringCellValue());
ResultSet Rs = st.executeQuery();

Java MySQL ODBC PreparedStatement cutting off query

`I am having a problem with doing a PreparedStatement for Java ODBC MySQL. It seems to be cutting off the query, and giving a syntax error. I am not sure how to proceed, as I am only learning Java SQL at this point. I can't really do a self contained example because the problem involves databases, and it would get quite big.
The code with the problem is this..
public void insertEntry(
Hashtable<String, String> strings,
Hashtable<String, Integer> integers,
Date created, Date paid, boolean enabled)
throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String dburl = "jdbc:mysql://" + dbHost + "/" + dbName +
"?user=" + dbUser + "&password=" + dbPass;
connect = DriverManager.getConnection(dburl);
ps = connect.prepareStatement("INSERT INTO " + dbName + ".users INSERT " +
"enabled=?, username=?, created=?, paid=?, alias=?, password=?, " +
"email=?, bitmessage=?, torchat=?, reputation=?," +
"privacy=?, fpmport=?, fpm-template=? ;");
java.sql.Date SQLcreated = new java.sql.Date(created.getTime());
java.sql.Date SQLpaid = new java.sql.Date(paid.getTime());
System.out.println("Debug: SQLpaid = " + SQLpaid.toString());
ps.setBoolean(1, enabled);
ps.setString(2, strings.get("username"));
ps.setDate(3, SQLcreated);
ps.setDate(4, SQLpaid);
ps.setString(5, strings.get("alias"));
ps.setString(6, strings.get("password"));
ps.setString(7, strings.get("email"));
ps.setString(8, strings.get("bitmessage"));
ps.setString(9, strings.get("torchat"));
ps.setInt(10, integers.get("reputation"));
ps.setInt(11, integers.get("privacy"));
ps.setInt(12, integers.get("fpmport"));
ps.setString(13, strings.get("fpm-template"));
ps.executeUpdate();
ps.close();
connect.close();
resultSet.close();
}
I get the following output when trying to use this method...
Debug: SQLpaid = 1990-03-21
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorEx ception: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT enabled=0, username='default_username', created='2000-03-21', paid='1990-' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInsta nce0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInsta nce(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newI nstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Construc tor.java:532)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:41 1)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLErro r.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.ja va:4237)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.ja va:4169)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:26 17)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java :2778)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionIm pl.java:2834)
at com.mysql.jdbc.PreparedStatement.executeInternal(P reparedStatement.java:2156)
at com.mysql.jdbc.PreparedStatement.executeUpdate(Pre paredStatement.java:2441)
at com.mysql.jdbc.PreparedStatement.executeUpdate(Pre paredStatement.java:2366)
at com.mysql.jdbc.PreparedStatement.executeUpdate(Pre paredStatement.java:2350)
at database.Users.insertEntry(Users.java:297)
at test.dbUsers.main(dbUsers.java:95)
i think your doing some mistake in your code:
these are following as:
1. your mention INSERT and you should must change like SET
2. your adding the ;in your SQL Query you should remove that.
your code:
ps = connect.prepareStatement
("INSERT INTO " + dbName + ".users INSERT " #look here error to change 'set' +
"enabled=?, username=?, created=?, paid=?, alias=?, password=?, " +
"email=?, bitmessage=?, torchat=?, reputation=?," +
"privacy=?, fpmport=?, fpm-template=? ; " #remove this semicolon(;));
you should must change like as:
ps = connect.prepareStatement
("INSERT INTO " + dbName + ".users SET " +
"enabled=?, username=?, created=?, paid=?, alias=?, password=?, " +
"email=?, bitmessage=?, torchat=?, reputation=?," +
"privacy=?, fpmport=?, fpm-template=? ");
Change:
INSERT INTO " + dbName + ".users INSERT "
To:
INSERT INTO " + dbName + ".users SET "
Refer to:
MySQL: INSERT Syntax
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name,...)]
SET col_name={expr | DEFAULT}, ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]

SQL update statement in Java

I am trying to update a field in my table using Netbeans and I have two conditions. The update statement is as follows:
String sql1 = "update tbl_log set Logout_Time =? where Firstname = ? and Check = ?";
try{
pst = conn.prepareStatement(sql1);
pst.setString(1, time);
pst.setString(2, username);
pst.setString(3, "IN");
pst.execute();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
but I am getting the following error:
com.mysql.jdbc.exceptions.jdbc4.MySQL SyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Check = 'IN' at line 1
How can I solve it?
"Check" is a reserved word, so you need to put it in backticks
Change it to:
String sql1 = "update tbl_log set Logout_Time =? where Firstname = ? and `Check` = ?";
For a list of reserved words, see here: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Try using
pst.executeUpdate();
and also
is pst a PreparedStatement?
if not change it to that...
st.executeUpdate("update reservation set busname='" +
jTextField10.getText() + "',busno='" +
jTextField9.getText() + "',cusname='" +
jTextField8.getText() + "',noofpass='" +
jTextField7.getText() + "',amount='" +
jTextField6.getText() +"' where cusname='" +
jTextField8.getText() + "' ");

what's wrong with my insert statement? mysql java

what's wrong with my insert method?
my table has two columns, name, and artist..and timestamp, that too
actually, how do i pass timestamp argument to the insert statement?
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
/*FileWriter dir = new FileWriter(nameOfSong.getText()
+ ".txt");
BufferedWriter buffer = new BufferedWriter(dir);
buffer.write(nameOfSong.getText());
buffer.newLine();
buffer.write(artist.getText());
buffer.newLine();
buffer.newLine();
buffer.write(lyrics.getText());
buffer.close();
*/
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO lyrics1_lyrics1 VALUES(" +
nameOfSong.getText() + ", " + artist.getText() + "");
} catch (Exception z) {
System.err.println("Error: " + z.getMessage());
}
internalFrame.dispose();
}
});
)
Always use PreparedStatement.
String sql="INSERT INTO lyrics1_lyrics1 VALUES (?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1,nameOfSong.getText());
statement.setString(2,artist.getText());
statement.executeUpdate();
statement.close();
connection.close();
The text values need to be surrounded by single quotes ('').
And SQL-escaped to avoid SQL injection attacks, or the first time you have a song by Little Bobby Tables, all your DB are belong to him.
Better yet, use a PreparedStatement, and let the machine do work for you.
You can use prepared statement for it
String query = "INSERT INTO lyrics1_lyrics1(name, artist, timestamp) values(?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, name); // set input parameter 2
pstmt.setString(2, artist);
pstmt.setString(3, new TimeStamp(new Date().getTime()));
You need to add an import statement for the TimeStap;
import java.sql.Timestamp;
or else use
pstmt.setString(3, new java.sql.TimeStamp(new Date().getTime()));
Example: Prepared Statement Insert.
You can find a lot of example in java2s site.
Change the line to:
statement.executeUpdate("INSERT INTO lyrics1_lyrics1 VALUES('" +
nameOfSong.getText() + "', '" + artist.getText() + "'");
This might solve your problem:
statement.executeUpdate("INSERT INTO lyrics1_lyrics1 VALUES('" + nameOfSong.getText() + "', '" + artist.getText() + "')");`

Categories

Resources