how to insert variable into a table in MySQL - java

I know how to add data into a table. Like
String insertQuery = "INSERT INTO tablename (x_coord, y_coord)"
+"VALUES"
+"(11.1,12.1)";
s.execute(insertQuery);
11.1 and 12.1 can be inserted into table. Now given a float variable
float fv = 11.1;
how to insert fv into the table?

In JAVA, you can use prepared statements like this:
Connection conn = null;
PreparedStatement pstmt = null;
float floatValue1 = 11.1;
float floatValue2 = 12.1;
try {
conn = getConnection();
String insertQuery = "INSERT INTO tablename (x_coord, y_coord)"
+"VALUES"
+"(?, ?)";
pstmt = conn.prepareStatement(insertQuery);
pstmt.setFloat(1, floatValue1);
pstmt.setFloat(2, floatValue2);
int rowCount = pstmt.executeUpdate();
System.out.println("rowCount=" + rowCount);
} finally {
pstmt.close();
conn.close();
}

I recommend you use a Prepared Statement, as follows:
final PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO tablename (x_coord, y_coord) VALUES (?,?)");
stmt.setFloat(1, 11.1f);
stmt.setFloat(2, 12.1f);
stmt.execute();

Related

Prepared statement execute query error (com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException)

I have written a simple method to get a string out of the database:
public String getUserString(int id, String table, String column) {
String output = null;
try {
String sql = "SELECT ? FROM ? WHERE id=?;";
PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
preparedStatement.setString(1, column);
preparedStatement.setString(2, table);
preparedStatement.setInt(3, id);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
output = resultSet.getString(column);
}
} catch (SQLException e) {
e.printStackTrace();
}
return output;
}
But when I try to use it like this: coreMySQL.getUserString(1, "economy", "balance");
I get this error:
https://pastebin.com/BMAmN4Xh
You can't set table name and column names with setXxx method(s) for PreparedStatement. It can only be used to set the values.
However, you can do a simple String replace to substitute table names and column names, e.g.:
String query = SELECT <column> FROM <table> WHERE id=?;
String sql = query.replaceAll("<column>", column).replaceAll("<table>", table);
PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
output = resultSet.getString(column);
}
Define a query template as:
String queryTemplate = "SELECT %s FROM %s where id = ?;";
// Inside Function:
PreparedStatement preparedStatement = getConnection().prepareStatement(String.format(template, column, table));
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();

JDBC does not Inserting data into mysql table

I have problem with inserting data into mysql table. JDBC doesnt inserting data into mysql table.
JDBC should get value from input "liczbaUzytkownikow" and "data from table form which contains informations about "termin" (Exactly: termin.nazwaObiektu, termin.adresObiektu, termin.dzien, termin.odKtorej and termin.doKtorej).
Here is code of this JDBC:
conn = ConnectionClass.Polacz();
ArrayList<Rezerwacja> rezerwacje = new ArrayList<Rezerwacja>();
PreparedStatement st = null;
ResultSet rs = null;
String sql = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values ('" + liczbaUczestnikow + "','" + idTermin + "')"
+ "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = '"+ idTermin +"'";
try
{
st = conn.prepareStatement(sql);
rs = st.executeQuery();
while(rs.next())
{
Rezerwacja rezerwacja = new Rezerwacja();
rezerwacja.setLiczbaUczestnikow(rs.getInt(1));
rezerwacja.setIdTermin(rs.getInt(2));
rezerwacje.add(rezerwacja);
}
}
catch(SQLException e)
{
System.out.println(e);
}
Any suggestions ?
You should use PreparedStatement to avoid sql injection attacks.
Furthermore your sql is wrong:
String sql = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values ('" + liczbaUczestnikow + "','" + idTermin + "')"
+ "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = '"+ idTermin +"'";
you cannot execute two different statements in a single batch.
In your case an Insert and an Update.
Create two PreparedStatement's:
String sql1 = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values (?,?)";
String sql2 = "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = ?";
PreparedStatement preparedStatement1 = con.prepareStatement(sql1);
preparedStatement1.setString(1, liczbaUczestnikow );
preparedStatement1.setInt(2, idTerminal);
PreparedStatement preparedStatement2 = con.prepareStatement(sql2);
preparedStatement2.setInt(1, idTerminal);
preparedStatement1.executeUpdate();
preparedStatement2.executeUpdate();

Inserting auto generated id in sqllite using java [duplicate]

This question already has an answer here:
How to perform an SQL insert in Java
(1 answer)
Closed 7 years ago.
I am writing java application using sqllite
public Product createProduct(String productName) throws SQLException {
String query = "INSERT into tbl_Product (name) values (?) ";
PreparedStatement preparedStatement = null;
Connection connection = null;
ResultSet rs = null;
Product product = null;
try {
connection = ConnectionFactory.getConnection();
preparedStatement = connection.prepareStatement(query);
//preStatement.setInt(1, 0);
preparedStatement.setString(1, productName);
preparedStatement.executeUpdate();
} finally {
//preparedStatement.close();
DbUtil.close(rs);
DbUtil.close(preparedStatement);
DbUtil.close(connection);
}
return product;
}
My product table have (ID,Name) column, where Id is auto generated. What all java changes are required so that preStatement can insert auto generated id in db.
String query = "INSERT into tbl_Product values (?) ";
ResultSet rs = null;
Product product = null;
try {
connection = ConnectionFactory.getConnection();
preStatement = (PreparedStatement) connection.prepareStatement(query);
preStatement.setString(1, productName);
rs = preStatement.executeQuery();
String sqlQuery = "INSERT into tbl_Product values (?)
PreparedStatement stmt = conn.prepareStatement(sqlQuery);
stmt.setString( 1, "val" ); //nameText variable contains the text of the jtextfield)
stmt.executeUpdate();
use execute update instead of execute query.
executeQuery():
Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.
executeUpdate():
Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.

How to write prepareStatement in Java

i want to use getParameter to get in Strings and ints and put them in a database using prepareStatement and SQL. It gives me errors with setString and setInt.
try {
String id = request.getParameter("clientid");
String cname = request.getParameter("clientname");
String address = request.getParameter("address");
String phonemodel= request.getParameter("phonemodel");
String imei = request.getParameter("imei");
String problem = request.getParameter("problem");
String date2 = request.getParameter("date");
String comments1= request.getParameter("comments");
int clientid = Integer.parseInt(id);
int imeino = Integer.parseInt(imei);
// int date1 = Integer.parseInt(date2);
Statement pstmt;
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app" , "app");
pstmt=con.prepareStatement("Insert into movilapp(id,clientname,address,modle,imei,problem,date,comments) values(?,?,?,?,?,?,?,?)");
pstmt.setInt(1,clientid);
pstmt.setString(2,cname );
pstmt.setString(3,address);
pstmt.setString(4,phonemodel);
pstmt.setInt(5,imeino);
pstmt.setString(6,problem);
pstmt.setString(7, comments1);
pstmt.executeUpdate();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
You called con.prepareStatement to get a PreparedStatement, but then you assigned it to a variable of type Statement, so Java doesn't know that there is a PreparedStatement-specific method setString.
Assign it to an actual PreparedStatement variable, by changing the declaration type of pstmt from
Statement pstmt;
to
PreparedStatement pstmt;
*IF Use Statement Then its syntax is *
Statement stmt = null;
stmt = conn.createStatement( );
String sql = "UPDATE Employees set age=30 WHERE id=103";
stmt.executeUpdate(sql);
And for PreparedStatement it is
PreparedStatement pstmt = null;
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
psmt.setInt(1,30);
psmt.setInt(2,1003);
psmt.executeUpdate(SQL);
So change Statement pstmt; to PreparedStatement pstmt = null; And it will work.

How to use java variable to insert values to mysql table?

Hi i am trying to insert the values in to mysql table. i am trying this code.
i have assigned values to variable and i want to pass that variable to that insert statement.
Is this correct?
code
int tspent = "1";
String pid = "trng";
String tid = "2.3.4";
String rid = "tup";
String des = " polish my shoes!";
INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"');
here is what i have tried, but i am not able to insert values
try
{
conn=DBMgr.openConnection();
String sqlQuery = "INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"');";
st = conn.createStatement();
rs = st.executeQuery(sqlQuery);
}
You should use executeUpdate() method whenever your query is an SQL Data Manipulation Language statement. Also, your current query is vulnerable to SQL Injection.
You should use PreparedStatement:
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUES (?, ?, ?, ?, ?)");\
Then set the variables at those index:
pstmt.setString(1, pid);
// Similarly for the remaining 4
// And then do an executeUpdate
pstmt.executeUpdate();
Try this,
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/dbname";
String uname="username";
String pass="password";
Class.forName(driver);
Connection c=(Connection) DriverManager.getConnection(url,uname,pass);
Statement s=c.createStatement();
s.executeUpdate("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"')");
Use a PreparedStatement and set the values using its setXXX() methods.
PreparedStatement pstmt = con.prepareStatement("INSERT INTO `time_entry`
(pid,tid,rid,tspend,description) VALUE
(?,?,?,?,?)");
pstmt.setString(1, pid );
pstmt.setString(2, tid);
pstmt.setString(3, rid);
pstmt.setInt(4, tspent);
pstmt.setString(5,des );
pstmt.executeUpdate();
import java.sql.*;
class Adbs1{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/rk","root","#dmin");
//here rk is database name, root is username and password
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into emp values('rk11','Irfan')");
// stmt.executeUpdate("delete from emp where eid ='rk4'");
//stmt.executeUpdate("update emp set ename='sallu bhai' where eid='rk5'");
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

Categories

Resources