JDBC - NetBeans x MySQL - java

I'm trying to create a Java Application in NetBeans which allows the user to use most MySQL RDBMS functionalities through a GUI. I have successfully written the code for the following :
Creating a Database
Dropping a Database
Creating a Table giving options for table name, no. of columns, data type for every column
I'm stuck at the part where the user gets to insert a record in the table that was just created. I'm unable to figure out how the "insert into table values ..." query can be dynamically created and passed depending on the table the user wants to enter this record in. The table could have any number of columns, of course.

I dont know if this is the correct method, but when I faced this same problem in the past, this is how I solved it :
I ran this query to find the number of columns in the table
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_catalog = 'database_name' AND table_name = 'table_name'
Then created a dynamic sql query based on no of columns:
String sql = "Insert into tablename values(";
for(int i = 1;i<=columns;i++){
sql += "?";
if (i < columns) {
sql += ", ";
}
}
sql+=");";
Then fired a Prepared Statement
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
If you also don't know the constraints and datatype of the columns, try parsing
desc tablename
I know this must be the shittiest workaround, but it worked for me;)

Related

Derby Embedded database strange behaviour, SQLSyntaxErrorException

I've got an embedded database in a Java project with a table TOOLS_IMAGES with two columns "TOOL_id" (int) and "TOOL_image" (blob).
I try to get the blob with following code:
rs = stmt.executeQuery("SELECT * FROM 'TOOLS_IMAGES' WHERE 'TOOL_id' = " + id);
The program trys to get like 15 different images at this way one after another. When I run the program it sometimes manages to get one image, sometimes two, sometimes even six, but at one point it always throws following exception. And after that one fail, it throws this exception for every following image:
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "\'TOOLS_IMAGES\'" at line 1, column 15.
Caused by: ERROR 42X01: Syntax error: Encountered "\'TOOLS_IMAGES\'" at line 1, column 15.
Why do I use apostophes in the SQL query? I already tried it without them, but here sql converts all my lowercases in the query to uppercases and complains afterwars that it can't find that column -.-
Looks like this:
rs = stmt.executeQuery("SELECT * FROM TOOLS_IMAGES WHERE TOOL_id = " + id);
and
java.sql.SQLSyntaxErrorException: Column 'TOOL_ID' 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 'TOOL_ID' is not a column in the target table.
Caused by: ERROR 42X04: Column 'TOOL_ID' 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 'TOOL_ID' is not a column in the target table.
Edit:
Here's the script, which I used to create the table
create table TOOLS_IMAGES
(
"TOOL_id" INTEGER not null
constraint TOOLS_IMAGES_PK
primary key,
"TOOL_mask" BLOB,
"TOOL_img" BLOB
);
Try to use:
ResultSet rs = stm.executeQuery("SELECT * FROM TOOLS_IMAGES WHERE \"TOOL_id\" = " + 1);
If you put:
rs = stmt.executeQuery("SELECT * FROM TOOLS_IMAGES WHERE TOOL_id = " + id);
It will be processed by Derby like :
rs = stmt.executeQuery("SELECT * FROM TOOLS_IMAGES WHERE TOOL_ID = " + id);
which are not the same
For more info visit

Unable to get count of table rows using jdbc - for JDEdwards table

I am trying to get the total count of a table rows using the below code.
Connection con = getJdeConnection(userN, password, hostN, dbName);
PreparedStatement p = con.prepareStatement("select count(*) from F0010");
System.out.print("\n----- Connection Success ---------------\n\n");
ResultSet rs = p.executeQuery();
if(rs.next()){
System.out.println("Query = select count(*) from F0010");
System.out.println("count = "+rs.getInt(1));
}else{
System.out.println("zero records");
}
The above code is running fine if am running the above code for my test table. Means it is giving the exact count. But I need to count number of rows in the above table F0010. This is a table in JD Edwards, contains 5203 records. The same sql when am running in JDE sql prompt it is giving count as 5203. But when am running this query from java code it is giving count as 0 (Zero).
My program is not throwing any exceptions.
Please help me. Thanks in advance.
Just to be sure you are running the query on the right schema change it into select count(*) from PRODDTA.F0010
where PRODDTA is the owner of your table.

SQL works from PMA but not Java

I have a prepared statement like so:
CREATE TABLE IF NOT EXISTS ? (uuid VARCHAR(128), item VARCHAR(48), value FLOAT, UNIQUE (uuid))
If I execute this directly in PMA, but replacing the ? with any text text, it works perfectly and it creates the table correctly. However, if I run it from Java it doesn't work.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Murder_PlayerData' (uuid VARCHAR(128), item VARCHAR(48), value FLOAT, UNIQUE (u' at line 1
Here's the Java code
String table = "Murder_PlayerData";
String execute = "CREATE TABLE IF NOT EXISTS ? (uuid VARCHAR(128), item VARCHAR(48), value FLOAT(11), UNIQUE (uuid))";
PreparedStatement statement = sql.getConnection().prepareStatement(execute);
statement.setString(1, table);
statement.execute();
Why does it work in PMA but not when I do it from Java?
Prepared statements can't be used to define table names, but to define values related to columns (insert values, values for where or having conditions, etcetera). One way to understand it is: Prepared Statements are for DML operations, not for DDL operations.
If you want to build a table on runtime, you need to build the SQL statement "by hand":
String table = "Murder_PlayerData"
String strSQL = "create table if not exists " + table + "("
// Add your column definitions
+ ")"
Statement stmt = conn.createStatement();
stmt.execute(strSQL);
Notice that, if the variable table can be filled with data provided by the user, your code will be vulnerable to SQL Injection Attacks. I recommend you don't create tables if their names must be provided by users, but rather create the tables without any user interaction and then insert the values, using some kind of key to identify which records belong to each user.

Java and MYSQL Syntax Issue

I'm trying to insert data into my MYSQL databse. I want to insert an int into the database which I have no problem doing. However, I want to INSERT INTO (VALUES) WHERE. I get a MYSQL syntax error when I try this.
I can INSERT and SELECT WHERE as long as they are in two seperate statements. Here is my code:
String query = ("INSERT INTO `accounts` (inventory) " + "VALUES ('"
+ Inventory.inventory + "') WHERE username='" + Frame.username
+ "' and password = '" + Frame.password + "'");
Basically, an INSERT statement can not have a WHERE clause. I am thinking that you want to UPDATE a certain record, eg
UPDATE accounts
SET inventory = 'valueHere'
WHERE userName = 'userHEre' AND password = 'passHere'
The only time an INSERT statement can have a WHERE clause is when you are inserting records from the result of a SELECT statement, eg
INSERT INTO tableName (col1, ..., colN)
SELECT col1, ..., colN
FROM table2
// WHERE ..your conditions here..
As a sidenote, your current coding style is vulnerable with SQL Injection. Consider using PreparedStatement.
Basic example of a PreparedStatement
String updateString = "UPDATE accounts SET inventory = ? WHERE userName = ? AND password = ?";
PreparedStatement updateStmt = con.prepareStatement(updateString);
updateStmt.setString(1, Inventory.inventory);
updateStmt.setString(2, Frame.username);
updateStmt.setString(3, Frame.password);
updateStmt.executeUpdate();
JDBC PreparedStatement
MySQL INSERT Syntax does not support the WHERE clause so that's why you have a syntax issue. Maybe you're looking for an UPDATE :
UPDATE [LOW_PRIORITY] [IGNORE] tbl_name
SET col_name1=expr1 [, col_name2=expr2 ...]
[WHERE where_definition]
[ORDER BY ...]
[LIMIT row_count]
Not a direct answer but more of a best practice....
You should avoid doing this type of string concatenation for any sql. You vulnerable to sql injection and it does not scale well. Instead you should look at using JdbcTemplates or NamedJdbcTemplate using the opensource spring framework.
The WHERE is not applicable in INSERT INTO Syntax. You want insert a new row in the table, and you should add the username and password as well as Inventory.inventory in VALUES set.

JTable not showing the column names set in the AS part of the SQL prepared statement

I know how to manually set JTable column names, but wondering if there was better way because presently I have a prepared sql statement which selects from DB with column names made to show up as different name using the AS 'New Column Name', but the names in the AS part are not showing up, just the standard DB column names... Is that supposed to work that way or is there a better way apart from manually setting column header names using the getColumnModel().getColumn(2).setHeaderValue("NEW NAME") ... ? Thanks
The ResultSetMetaData method getColumnLabel() should provide the text from a given SELECT AS label. For example,
PreparedStatement ps = conn.prepareStatement("SELECT name AS moniker, …");
ResultSet rset = ps.executeQuery();
while (rset.next()) {
String name = rset.getString(1);
System.out.println(rset.getMetaData().getColumnLabel(1)+ ": " + name …);
}

Categories

Resources