i'm getting an sqlite mismatch exception while inserting data into database.i m creating an app in netbeans but when i try to update database by selecting textfields by clicking button its showing this exception.
private void calculationDBActionPerformed(java.awt.event.ActionEvent evt) {
String sql2 = "Insert into Calculation_Info (prodID,item_name,net_amount,tax_rate,Amt_Of_Product,Grand_Total) values(?,?,?,?,?,?)";
try{
pst = conn.prepareStatement(sql2);
pst.setString(1, prodID.getText());
pst.setString(2, txtPRoduct.getText());
pst.setString(3, txtTotal.getText());
pst.setString(4, txtTaxTotal.getText());
pst.setString(5, txtAmountTotal.getText());
pst.setString(6, txtGrandTotal.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Gotcha Bro!");
pst.close();
rs.close();
}catch(Exception exc){
JOptionPane.showMessageDialog(null, exc);
}
}
You can't set String for an Int of real type, for that you get this type of error, so you have to convert your inputs to the right type, for example :
prodID.getText() should be an int and not a String so you have to use it like so:
pst.setInt(1, Integer.parseInt(prodID.getText()));
//--^^^^^----------^^convert your String to int and change setString to setInt
The same thing for the rest.
#YCF_L explains the problem correctly. I believe the issue that you have #Muhammad Quanit is that you are not understanding what your query is asking for and what you're trying to pass into the query.
To break it down for you, your query:
"Insert into Calculation_Info (prodID,item_name,net_amount,tax_rate,Amt_Of_Product,Grand_Total) values(?,?,?,?,?,?)"
Takes 6 values that you have to provide (Please NOTE the type of each they take in):
prodID (int)
item_name(String)
net_amount(double)
tax_rate(BigDecimal)
Amt_Of_Product(int)
Grand_Total(BigDecimal)
In your program, you have 6 text boxes that will obtain these values to put in HOWEVER when you call the method: getText() it returns a String type. So when we try to put String prodID = "3" into our SQL query, you would receive the error you originally received: datatype mismatch. Now your current problem is: java.lang.numberFormatException : for input String. This means that you are trying to convert a String value into a number; however it is FAILING. So what could be possible reasons for this? Well...
/* Lets say I have a string with value 4.7*/
String s = "4.7";
/* Lets try to parse this using parseInt method*/
Integer.parseInt(s); //NumberFormatException -- because 4.7 cannot be converted into an int
/* How about if my string was a word/phrase?*/
String s = "foo";
/* Attempt to parse...*/
Integer.parseInt(s); //NumberFormatException -- because "foo" cannot be converted into integer
Double.parseDouble(s); //NumberFormatException -- because "foo" cannot be converted into a double
So as you can see, you have to be very careful and keep track of what you are converting and passing into your query (and vice versa).
As #YCF_L mentioned, perhaps your String contains white spaces at the start or end. There is a method called trim() in the String class that will help you with that.
/* Let's call the getText() method to obtain our string */
String s = item_name.getText(); // s = " Foo Bar "
/* NOTE: the white spaces (' ') BEFORE and AFTER the String we want*/
System.out.println(s.trim()); // Prints out "Foo Bar"
So the String OBJECT has a method called trim() which gets rid of TRAILING and LEADING white spaces, but NOT white spaces in between. So instead of getting " Foo Bar ", we will get "Foo Bar".
I upvoted #YCF_L 's answer -- he deserves the credit. I just wanted you to understand this concept since you were still confused after his explanation followed by receiving the NumberFormatException.
Editted to include the trim() method that was mentioned in the comments.
Related
I have a special table in my database where I store the message key - value in the form, for example: question first - How are you, ...?
Now I want to insert for example a name at the end of the question. I don't need a hardcode, I want to do it through some formatting. I know that there is an option to insert text through % or ?1 - but I don't know how to apply this in practice. How are you, % or (?1)?
And what if I need to insert text not only at the end, but also in the random parts:
Hey, (name)! Where is your brother, (brothers name)?
You can insert a String into another String using the String.format() method. Place a %s anywhere in the String where you want and then follow the below syntax. More information here.
String original = "Add to this pre-existing String";
String newString = String.format("Add %s to this pre-existing String", "words");
// original = "Add to this pre-existing String"
// newString = "Add words to this pre-existing String"
In your specific situation, you can store the names as other Strings and do this:
String name = "anyName";
String brothers_name = "anyBrotherName";
String formattedString = String.format("Hey, %s! Where is your brother, %s?", name, brothers_name);
How about this?
String.format("Hey, %s! Where is your brother, %s?","Sally", "Johnny");
For using the %, first you will need to create another variable of type string in which you store the text you want to print.
Example:
String a="Alice";
String b="Bob";
String str=string.format("Hey, %s! Where is your brother, %s?"a,b);
System.out.println(str);
Output:
Hey Alice! Where is your brother, Bob?
You can get more information about this here
I have a strange scenario. Query string has value first=second=12123423423423432323234
String queryString = request.getParameter("first=second=12123423423423432323234")
So i have to:
capture 'first' and 'second' values
validate the query string has 'first' and 'second'.
Could someone please share how I can achieve this in the best possible way?
I really appreciate your help on this.
I believe your query string should look like
first=firstvalue&second=secondvalue
You can use this in your servlet to print the query string
String firstValue = request.getParameter("first");
String secondValue = request.getParameter("second");
System.out.println("Query String:first="+firstValue+"second=+"secondValue);
In your case, where the query string is
first=second=12123423423423432323234
You could do this
String first = request.getParameter("first");
String second = request.getParameter("second");
if(first.contains("second=")){
second = first.split("second=")[1];
first = first.split("second=")[0];
}
out.println("[First:"+first+"][Second:"+second+"]");
If your parameters are separated properly by & (i.e. first=&second=something), then simply .getParameter("first") and .getParameter("second")
Otherwise, you'd need to play with the string - probably split around =, and for the value of first cut until second is encountered. Though I fail to see how will that work if first has a value: first=foosecond=bar?
I want to get string from column no. 4 from my database to check user privileges.
Can I use rs.getString(index) to get data from column no.4?
I want to check user´s privileges...so if the column data is equal 4, the page will be redirected to AdminControlPanel.jsp
BUT, this code doesn´t work :(
String user=request.getParameter("login");
String pass=request.getParameter("password");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/android","root","root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from users where login='"+user+"' and password='"+pass+"'");
String p = rs.getString(4);
int count=0;
while(rs.next()){
count++;
}
if(count>0 && p == "4"){
// out.println(rs);
response.sendRedirect("AdminControlPanel.jsp");
}
else{
out.println("aaa");
response.sendRedirect("#");
}
}
catch(Exception e){
System.out.println(e);
}
you are comparing two String objects rather than checking the values in the String.
just change the code to p.equals("4") and try.
String p = rs.getString(4); // This should be inside your while
int count=0;
while(rs.next()){
count++;
}
You should move your first line inside your while loop. You can't
fetch the columns of a row, until you move your cursor to that row
using res.next().
Also, since your database should ideally have only one record for a
combination of username and password. So, you can better use an
if instead of while.
And you don't really need a count variable there.
So, your code should be: -
ResultSet rs=st.executeQuery("select * from users where login='"+user+"' " +
"and password='"+pass+"'");
if (rs.next()) {
String p = rs.getString(4); // Note that using Column name is a better idea
// or rs.getInt(4) if the column type is `int`
if(p.equals("4")) { // Use equals method to compare string content
response.sendRedirect("AdminControlPanel.jsp");
} else{
out.println("aaa");
response.sendRedirect("#");
}
}
Also, note that you should compare your string using equals method. if (p == "4") will give you false result. == operator does not compare the content of the string, rather the content of the reference used in comparison.
You want
while (rs.next()) {
String val = rs.getString(4);
....
Note that iterating through a ResultSet iterates through the rows. For each row, the column indexing starts from '1'.
However it's safer to get by column name, since your SQL query doesn't specify neither the columns nor the order in which they're returned:
String val = rs.getString("COLUMN_NAME");
I see from the below that you need an integer. Check out the doc for ResultSet for more info, but:
int val = rs.getInt("COLUMN_NAME");
As an aside, I don't see you closing your ResultSet/Statement/Connection in the above. If you're not, then you'll need to!
In my Oracle table there are columns with different type.
I want to read all columns as number.
String str = resultSet.getString("col1");
The problem is that if column in database is defined as number, and value is
0.5
the returned string will be
.5
I can not use any other getter like getDecimal() and etc.
If I use:
String str = resultSet.getObject("col1").toString();
I'll get an exception if the value is null.
You could use
String str = String.valueOf(resultSet.getObject("col1"));
as a simple workaround to avoid any exceptions. (Not sure why you can't use resultSet.getDouble("col1") though.)
If you don't want to see an empty string rather than the literal "null" for a null value (which is what String.valueOf()) will produce, you can use:
Object value = resultSet.getObject("col1")
String str = value == null ? "" : value.toString();
I want to generate a string such as sql command:
"INSERT INTO xxx VALUES(XXX, XXX, XXX)"
currently I use StringBuilder and some String constant like "INSERT INTO" to concatenate input String parameters for the table name and inserted values.
However, other than performance issue, this plain concatenation looks not elegant.
Is there any other way of doing this?
In my opinion, JDBC's prepared statement is one good example of such a "command template":
PreparedStatement pstmt=connection.createPreparedStatement("INSERT INTO ? VALUES(?,?,?)");
then you can set the table name and inserted value.
pstmt.setString(1,"tableA");
pstmt.setInt(2, 100);
...
However, I can not use prepared statement, since what I want is just String...
And someone give me some hint to use java.util.Regex or JavaCC to produce the String.
But as far as I can see, whatever is chosen for some code elegancy issue, Java String must be generated by something like StringBuilder, right???
You could use String.format():
String.format("insert into %s values('%s', '%s', '%s')", "user", "user123", "pass123", "yellow");
It's worth noting though, that any of these "string building" techniques leave you vulnerable to SQL injection attacks. You should really use JDBC parameterised queries wherever possible.
Edited to add quotes around strings.
Maybe you are looking for java.text.MessageFormat
int planet = 7;
String event = "a disturbance in the Force";
String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
planet, new Date(), event);
Have you tried just using '+' ?
String sql = "INSERT INTO " + table
+" VALUES(" + value1 + ", " + value2 + ", " = value3+")";
Given the variety of other answers and none of them met your approval, perhaps you should accept that the actual String generation (sans JPA, PreparedStatement, etc.) is going to be fairly inelegant and create a utility class with static sql generators.
edit Showing an example of how I'd go about this if a pre-existing class such as PreparedStatement weren't an option. It's not the most elegant, but it does what it's supposed to (assuming I typed it all in correctly).
public class SQLUtil {
public static String generateInsertSQL(String tableName, List<CustomParameter> parmList){
StringBuilder sb = new Stringbuilder();
sb.append("insert into ");
sb.append(tableName);
sb.append(" values (");
for (int i = 0; i < parmList.size(); i++){
customParameter parm = parmList.get(i);
switch (parm.getType()) { // enum with your desired sql types
case ParmTypes.String:
sb.append("'");
sb.append(StringEscapeUtils.escapeSql(String.valueOf(parm.getValue())));
sb.append("'");
break;
case ParmTypes.Integer:
sb.append(Integer.valueOf(parm.getValue()));
break;
}
if (i < parmList.size() - 1) sb.append(",");
}
sb.append(")");
return sb.toString();
}
}
This way, your business code will remain relatively elegant and you can play around with the SQL String generation to your heart's content. You can also use this to "guarantee" all your inserts are protected against such attacks as SQL injection.
Use StringTemplate (http://www.stringtemplate.org/) maybe a good choice:
This looks better, right?
StringTemplate insert = new StringTemplate("INSERT $table$ VALUES ($value; separator=\",\"$)");
insert.setAttribute("table", "aTable");
String[] values = {"1", "1", "'aaa'", "'bbb'"};
for(int i = 0;i < values.length;i++){
insert.setAttribute("value", values[i]);
}
System.out.println(insert.toString());