Insert an email address into MySQL using a java application - java

I am trying to insert an email address into a MySQL using a java application. The problem I am having is that the "#" character is causing a MySQLSyntaxErrorException. I try to insert the email address as a String. How do i fix this?

String insert = "INSERT INTO customer_tbl(name, email) VALUES (?,?)";
PreparedStatement ps = con.prepareStatement(insert);
ps.setString(1,"name");
ps.setString(2,"freddy#slabbinck.net");
ps.executeUpdate();
A prepared statement let you use placemarkers, which can be set to anything and is not parsed by the SQL parser. As an added bonus, this makes you also immune for SQL injection.

Parameterize your query using a PreparedStatement. This way you do not have to worry about manual string escaping and are less vulnerable to SQL injection attacks.

Try to use PreparedStatement like in this example: http://www.exampledepot.com/egs/java.sql/InsertPs.html

Related

How to insert a string with an apostrophe as the value of the mysql database field with java and j-connector?

I have a database with a "username" field and with Java I insert the values ​​into the database. I tried to enter the username "l'ornitorinco" but the program does not work (crashes). I know that when I insert an apostrophe string with phpMyAdmin like "l'ornitorinco" it is sent in this way "l'ornitorinco". I should probably analyze the string and insert the apostrophe at the appropriate point (with a for loop from 0 to string.length), but does anyone know a more appropriate method? I had read about a method to set the strings for mysql use, but I not remember.
You could use a PreparedStatement, as its setString() method allows you to include apostrophes on the value, making it much simpler than playing the single/doble quote game.
String queryString = "insert into username values (?)";
query = con.prepareStatement(queryString);
query.setString(1, "l'ornitorinco");
query.executeUpdate();
Take a look here for more info. Hope it helps!

SQL Query works in workbench but gives syntax error in java

I ran the query in both sql Workbench and in the executeUpdate() method in java:
in Workbench:
INSERT INTO recentsearches (name) VALUES ("blah");
in java:
statement.executeUpdate("INSERT INTO recentsearches (name) VALUES (\""+name+"\""));
Assuming name = "blah". But I get a syntax error from running the query in java, I've already checked the string value for name. It definitely comes up as "blah", and I didn't forget the speech marks around string values, yet I still get a syntax error.
The error I get in my console is:
check the manual that corresponds to your MySQL server version for the
right syntax to use near '' at line 1
Try to use:
"INSERT INTO recentsearches (name) VALUES("+name+")";
My advice, use PreparedStatement because it has:
-Precompilation and DB-side caching of the SQL statement leads to overall faster execution and the ability to reuse the same SQL statement in batches.
-Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters. Note that this requires that you use any of the PreparedStatement setXxx() methods to set the values

Inserting variables with SQL in Java

I'm writing a webpage that takes input from a form, sends it through cgi to a java file, inserts the input into a database through sql and then prints out the database. I'm having trouble inserting into the database using variables though, and I was wondering if anyone would be able to help me out.
String a1Insert = (String)form.get("a1");
String a2Insert = (String)form.get("a2");
This is where I get my variables form the form (just believe that it works, there's a bunch more back end but I've used this before and I know it's getting the variables correctly).
String dbURL = "jdbc:derby://blah.blahblah.ca:CSE2014;user=blah;password=blarg";
Connection conn = DriverManager.getConnection(dbURL);
Statement stmt = conn.createStatement();
stmt.executeUpdate("set schema course");
stmt.executeUpdate("INSERT INTO MEMBER VALUES (a1Insert, a2Insert)");
stmt.close();
This is where I try to insert into the databse. It give me the error:
Column 'A1INSERT' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification or appears in a HAVING clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE statement then 'A1INSERT' is not a column in the target table.
If anyone has any ideas that would be lovely ^.^ Thanks
java.sql.Statement doesn't support parameters, switching to java.sql.PreparedStatement will allow you to set parameters. Replace the parameter names in your SQL with ?, and call the setter methods on the prepared statement to assign a value to each parameter. This will look something like
String sql = "INSERT INTO MEMBER VALUES (?, ?)";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, "a1");
stmt.setString(2, "a2");
stmt.executeUpdate();
That will execute the SQL
INSERT INTO MEMBER VALUES ('a1', 'a2')
Notice the parameter indexes start from 1, not 0. Also notice I didn't have to put quotes on the strings, the PreparedStatement did it for me.
Alternatively you could keep using Statement and create your SQL string in Java code, but that introduces the possibility of SQL injection attacks. Using PreparedStatement to set parameters avoids that issue by taking care of handling quotes for you; if it finds a quote in the parameter value it will escape it, so that it will not affect the SQL statement it is included in.
Oracle has a tutorial here.

String truncation when using PreparedStatement and SetString with SQL Server

I'm trying to use PreparedStatement and setString to insert data into a TEXT field of a SQL Server DB. The statement is something like this:
PreparedStatement p = con.prepareStatement("insert into comments(comments) VALUES (?)");
p.setString(1, comment);
The insert is working correctly but being truncated after 200-some characters. An error is not thrown. I can't find reference to this being the case anywhere else. It's definitely coming from the Java side, I've tested longer inserts into the SQL db directly.
Ideas? Is there a way I could convert the string to a different data type maybe?

Specifying a variable name in QUERY WHERE clause in JDBC

Could someone please give me a link on how to create a query in JDBC that gets a variable name in the WHERE statement, or write an example, to be more specific, my code looks something like this:
private String getLastModified(String url) {
String lastModified = null;
ResultSet resultSet;
String query = "select LastModified from CacheTable where " +
" URL.equals(url)";
try {
resultSet = sqlStatement.executeQuery(query);
}
Now I need the syntax that enables me to return a ResultSet object where URL in the cacheTable equals url from the method's argument.
thanks
The easiest way would be
String query = "select LastModified from CacheTable where url = '" + url +"'";
You should use bind variables though:
String query = "select LastModified from CacheTable where url = ?";
prepStmt = conn.prepareStatement(query);
prepStmt.setString(1, url);
rs = prepStmt.executeQuery();
To take it one step further you should really use DBUtils from apache-commons or Sping JDBC framework. A lot of JDBC work is mundane and error prone due to the number of steps involved with it. Both links have working examples for you to get started.
These helper libraries will make your life much more comfortable :-).
To clear a misconception: JDBC and SQL are two entirely different things. Databases only understand the SQL language. It's a (semi)standard which you can learn here. JDBC is just a Java API which enables you to execute SQL language using Java code. Nothing less, nothing more. JDBC is not a Java way of writing SQL language or so. It's just the messenger between Java code and the database. You can learn JDBC here.
That said, yes, the PreparedStatement is the way to go to set values in a SQL query. It not only eases setting fullworthy Java objects in a SQL string using the setXXX() methods, but it also saves you from SQL injection attacks.

Categories