user2078258
user2078258

Reputation: 13

Inserting Integer Values into MySQL Database using Variables

     Class.forName("com.mysql.jdbc.Driver");
     Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
     "root", "mysecret");
     System.out.println("Connected to Database");
     Statement stmt1 = conn.createStatement();
     ResultSet rs1=null;
     String sql="insert into id
     values('"+name+"',12,+fs+,+se+,+th+,+ft+,+f+,+si+,+sv+,+ei+)";
     System.out.println("sql:"+sql);
     stmt1.executeUpdate(sql);     

The Name Variable is taken care of in the definition part not included here, the output is

     sql:insert into id values('Golum',12,+fs+,+se+,+th+,+ft+,+f+,+si+,+sv+,+ei+);

It also says error in SQL Syntax which refers to the variables fs,se,th,ft,f,si,sv and ei. Basically i am trying to pass integers to MySQL Database using variables. the definition of these variables is as such

    int fs = x21;
    int se = y21;

x21 and y21 store mouse click co-ordinates x and y respectively. The code below shows that the co-ordinates are passed correctly. The error is in SQL Syntax. I wanna Know what is the correct syntax for passing integers to SQL Database using this technique.

    System.out.println(fs);

Upvotes: 0

Views: 16836

Answers (3)

msfk
msfk

Reputation: 137

try this

String sql="insert into id values('"+name+"',12,"+fs +","+se+","+th+","+ft+","+f+","+si+","+sv+","+ei+")";

your syntax for using vars in the string is wrong. The vars should be out of quotations

Upvotes: 0

rgettman
rgettman

Reputation: 178263

You have a SQL error in your insert statement. I don't know why you have those + characters in your statement, but I'm guessing that you are attempting to concatenate the values into the statement. But in your attempt the + characters are part of the string. Try inserting double-quote characters to end and start the strings to concatenate together to form the insert statement:

String sql="insert into id values('"+name+"',12, " +
    fs+","+se+","+th+","+ft+","+f+","+si+","+sv+","+ei+")";

Of course anytime you concatenate values that may be from the user into a SQL statement, you are vulnerable to SQL injection. If these are user values, then use a PreparedStatement with bind variables instead.

Upvotes: 3

HeatfanJohn
HeatfanJohn

Reputation: 7333

You need to tell Java to convert your integer variables to strings, change your sql assignment statement to:

String sql="insert into id values('"
    + name + "',12," + fs + ", " + se + ","
    + th + "," + ft + "," + f + "," + si + "," + sv + "," + ei + ")";

Upvotes: 0

Related Questions