How to add blocks of text with punctuations in PostgreSQL - java

I am using java to execute postgresql statements. In one step, I need to create a table in which one column will store blocks of text (that may contain punctuation marks, such as comma, semi-colon, etc).
What data type do I use to populate this column?
For example, in the given example, I am creating a table called "MYTHOUGHTS", and that has a column called "THOUGHTS". I am trying the following code:
try {
con = DriverManager.getConnection(url, user, password);
System.out.println("Opened Database Successfully");
st = con.createStatement();
String sql = "CREATE TABLE MYTHOUGHTS " + "(ID INT PRIMARY KEY NOT NULL," + " THOUGHTS TEXT NOT NULL," + " Number INT NOT NULL," + " ADDRESS CHAR(50), " + " SALARY REAL)";
st.executeUpdate(sql);
sql = "INSERT INTO COMPANY (ID,THOUGHTS,AGE,ADDRESS,SALARY) " + "VALUES (1," + "This is life, as I see it. Do you think otherwise?" + ", 32, 'California', 20000.00 );";
st.executeUpdate(sql);
st.close();
con.close();
}
catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
I get the following error:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "life"
Position: 68
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2161)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1890)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:560)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:403)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:331)
at com.vivek.PostgreSQLExample.main(PostgreSQLExample.java:39)
org.postgresql.util.PSQLException: ERROR: syntax error at or near "life"
Position: 68
It is possible that TEXT data type is not appropriate. Please, let me know how I may add multiple lines of text that may have commas and periods into a column.
Thank you for your time and assistance. Highly appreciate it.

Use the text data type. The contents do not matter, the only thing you can't put in text is the null byte \0.
If you're having problems with the contents then you're running dangerous code that's doing direct string interpolation, instead of using parameterized statements. See: http://bobby-tables.com/ , http://en.wikipedia.org/wiki/SQL_injection, http://docs.oracle.com/javase/tutorial/jdbc/basics/

Related

Java SQLSyntaxErrorException at executeUpdate

I am creating a database that keeps track of Spiderman comic books. I am getting a SQLExecption at line 28:
stmt.executeUpdate(createstring);"
So I assume there is something wrong with the syntax of my SQL that is in the createstring but nothing jumps out at me.
Below is code
import java.sql.*;
import javax.swing.*;
public class SpidermanDatabase {
public static void main(String[] args)
{
String url = "jdbc:ucanaccess://c:/users/jeff/comics.accdb";
Connection con;
String createstring;
createstring = "CREATE TABLE Spider-Man (" +
"ComicName varchar(40), " +
"IssueDate varchar(40), " +
"IssueName varchar(40), " +
"MintCond varchar(40), " +
"IssueValue double(2,2), " +
"IssueNum int)";
Statement stmt;
try
{
con = DriverManager.getConnection(url, "", "");
stmt = con.createStatement();
stmt.executeUpdate(createstring);
JOptionPane.showMessageDialog(null, "Spider-Man table created", "SQL Statement Confirmation",
JOptionPane.INFORMATION_MESSAGE);
stmt.close();
con.close();
System.exit(0);
}
catch(SQLException ex)
{
System.out.println("SQLException");
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
}
Image attached is full error message
It appears to me that you are using Microsoft Access database. It also appears that you are using ucanaccess JDBC driver to connect to that database.
Your problem is that you are using an illegal character in the name of the table that you are trying to create. According to Microsoft documentation, identifiers, such as database table names, cannot contain a dash (-) (also known as a hyphen) – unless you enclose the identifier in either square brackets, i.e. [], or quotation marks.
Hence you should change the SQL create table string to the following:
createstring = "CREATE TABLE [Spider-Man] (" +
"ComicName varchar(40), " +
"IssueDate varchar(40), " +
"IssueName varchar(40), " +
"MintCond varchar(40), " +
"IssueValue double, " +
"IssueNum int)";
Also note that the double data type cannot have scale and precision qualifiers. Hence I also removed the (2,2) part from the data type for column IssueValue.
Remember that after this you must always write [Spider-Man] (or "Spider-Man") as the table name in all SQL statements. Alternatively, you could replace the dash with and underscore (_) which is a legal character in an identifier and thus do away with the need for square brackets (or quotation marks), i.e. name the table Spider_Man.
EDIT
Although the above CREATE TABLE statement is valid SQL, it appears that ucanaccess JDBC driver cannot handle it. The only way I got it to work was to replace the dash with an underscore.
Here is my java code for creating the database table Spider_Man.
(Note that the below code uses try-with-resources.)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcTst0 {
public static void main(String[] args) {
String url = "jdbc:ucanaccess://C:/users/jeff/comics.accdb";
String createstring = "CREATE TABLE Spider_Man (" +
"ComicName varchar(40), " +
"IssueDate varchar(40), " +
"IssueName varchar(40), " +
"MintCond varchar(40), " +
"IssueValue double, " +
"IssueNum int)";
try (Connection con = DriverManager.getConnection(url, "", "");
Statement stmt = con.createStatement()) {
stmt.executeUpdate(createstring);
System.out.println("Spider_Man table created");
}
catch (SQLException xSql) {
xSql.printStackTrace();
}
}
}

How to Delete rows in table using Variable in SQL

How should I delete a row using a java variable in SQL table?
I am trying to delete a record from table member (with two columns, name and year) using what the user has input (variable newName and newYear). I want to find the row that has the same record as what the user has input (name = newName && year=newYear) and delete it. However, this code doesn't change anything on the table (no row is deleted although what I have input is correct). What's wrong with my code?
String newName = memName.getText();
int newYear = parseInt(memYear.getText());
are the variables used in the code below.
try {
s = c.createStatement();
t = "DELETE FROM member " +
"WHERE (name='" + newName + "'&& year='" + newYear + "')";
s.executeUpdate(t);
s.close();
c.commit();
c.close();
} catch (SQLException ex) {
Logger.getLogger(AddMember.class.getName()).log(Level.SEVERE, null, ex);
}
JOptionPane.showMessageDialog(null, "Saved.");
memName.setText(null);
memYear.setText(null);
I want the row with the info the user input to be deleted from the table, but it didn't make any changes to my table.
the problem you have is that in SQL you cannot use && instead use AND as shown in the following code:
t = "DELETE FROM member " +
"WHERE (name='" + newName + "' AND year='" + newYear + "')";

how can i pass an sql query as a parameter to an other sql query in java?

Im writing a code to manage a cafe so in the frame i added a JTable where everytime i choose an item from a JComboBox it should show in the JTable. for this purpose i added a button and for its action i made sure every time i click it, it stores the item clicked from the JComboBox in a database and then from the database its fetched in the Jtable. But the problem is that the JTable has 2 columns while the choices from the JComboBox have only one. so the other column must be called from an other database which means i have to call an sql query inside of an other one and i don't know how to do that. Ive tried the code below but it gives me this error "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'produit' at line 1"
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/café", "root",
"ata1");
Statement statement = connection.createStatement();
ResultSet resultat = statement.executeQuery ( "SELECT prix FROM commande_existantes WHERE "+ cb.getSelectedItem() + "IN produit" );
Statement stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO commande_existante VALUES ('" + cb.getSelectedItem() + "'," +resultat+ ")");
} catch (Exception a) {
a.printStackTrace();
}
}
});
Chances are you want something like:
Statement statement = connection.createStatement();
ResultSet resultat =
statement.executeQuery ( "SELECT prix FROM commande_existantes " +
" WHERE produit = " + cb.getSelectedItem() );
if (rs.next) {
stmt.executeUpdate("INSERT INTO commande_existante VALUES " +
"('" + cb.getSelectedItem() + "'," +
resultat.getDouble("prix")+ ")");
}
I am assuming "produit" is a column name in "commande_existantes" - so you just want to find the row(s) where the value of "produit" is the one you have selected. In SQL, "IN" is used to find a value in a list that you specify after the "IN"... - but the query will already look at all the rows in that table looking for matches to your "WHERE" clause, so the "=" comparison is all you need.
A ResultSet potentially represents a table of values that are the answer to the query you ran - so you need to move to a row (using "next()") then get to the column value you want (in this case, using that call to "getDouble()".
You should look for an tutorial on JDBC, and in particular how to use parameters in SQL, rather than embedding the values in the SQL like you did here.
You can directly use as below:
String selected=cb.getSelectedItem();
stmt.executeUpdate("INSERT INTO commande_existante VALUES ('"+selected+"',(SELECT prix FROM commande_existantes WHERE '"+selected+" ' IN('produit') AND ROWNUM<2 ))");

Name requires more than 30 bytes in LATIN internal form?

I am trying to implement Fastload Utility with jdbc. But I keep getting the following error: Name requires more than 30 bytes in LATIN internal form
I read many articles : this error occurs during table creation. In my case this error is thrown at the executeBatch() line . Here is my code
Connection conn = DriverManager.getConnection(url, username, password); // I am using TYPE=FASTLOAD
// creating table
String createStr =
"CREATE TABLE dbname.tablename( " +
" Fname VARCHAR(506) CHARACTER SET UNICODE, " +
" Lname VARCHAR(507) CHARACTER SET UNICODE " +
" );"
Statement createTable = ...
createTable.execueQuery("CREATE TABLE ... ") ;
PreparedStatement prst = ... ;
while ( // loop ) {
prst.addBatch();
}
prst.executeBatch(); // Here it throws this error
conn.commit();
Why do I get this error when executeBatch() method fires ? What can I do ?
I believe FastLoad prefaces the column names with "F_", so your column names need to be 28 characters or less.
From the documentation:
The destination table column names must not exceed 28 characters.
Here's a link to the documentation.

JDBC UPDATE ERROR with MySQL - error code 1054

this is the code
PreparedStatement res1 = null;
String insertUser = "INSERT INTO users (uid,firstname,lastname,score) VALUES (" +
this.getFbUid() + "," +
this.getFbFirstName() + "," +
this.getFbLastName() + ",0)";
System.out.println(insertUser);
try
{
res1 = connection.prepareStatement(insertUser);
res1.executeUpdate();
System.out.println("executed query to db with the message" + res1);
}
catch(SQLException e)
{
System.out.println("setUserInDb: " +e.getMessage());
System.out.println("error num: " +e.getErrorCode());
}`
I'm getting error code 1054:
Unknown column 'Alon' in 'field list' when trying to insert the line "INSERT INTO users (uid,firstname,lastname,score) VALUES (123456,Alon,xyz,0)
In the db I have table users with varchar columns uid, firstname, lastname, and score.
What am I doing wrong?
Alon seems or type varchar should be under '
Use Prepared statement rather
Just as Jigar pointed it out,
When u insert String values into the table you should use the values inside single or double quote(' or ").
Eg 'Hello',"Hello".

Categories

Resources