How to create a table in MySQL when using java - java

I'm trying to create a table in mysql through java. I'm using putty for this by the way. Here is a bit of the code I have so far but it doesn't work.
rs=s.executeQuery("CREATE TABLE test(id CHAR(2),name VARCHAR(3),PRIMARY KEY(id)); ");
while(rs.next())
{
System.out.println(rs.getString(1));
}
catch (SQLException ex)
{
System.out.println("SQLException:"+ ex.getMessage());
}

executeQuery() is for quires (usually SELECT) that return a ResultSet.
With DML (and DDL) queries you need to use executeUpdate() method.
For more information and examples use Setting Up Tables tutorial.

See this post here: Data Manipulation Statements
You should be using executeUpdate() if you wish to actually modify the database.

Your query is ok! But you don't get a result set! the CREATE TABLE won't give an rows or columns.
You have been tricked be the documentation:
Returns:
a ResultSet object that contains the data produced by the given query; never null
however
Throws:
SQLException - if a database access error occurs,... the given SQL statement produces anything other than a single ResultSet object, ...
In my opinion a call of "execute" would be the proper way.

I don't think its ever a good idea to generate your database schema via Java. Use the utility tool that comes with your database to create your schema. This way, you or anyone (such as a DBA) can create your tables, views, indexes, constraints, grant permissions, etc without having to know Java. You can even have your database utility generate an SQL script that you can run to re-generate the schema from scratch. Last point: I believe you will be better off calling your primary key test_id and making it type numberic, long, or int. this way, when you refer to it as a foreign key in another table, you will immediately know it refers back to the test table.

Related

How to check if a table exists in jOOQ?

After opening a database connection, I want to check if the database is newly minted or not. I am using H2 which automatically creates a DB if one doesn't exist.
I tried this check:
db.Public.PUBLIC.getTables().isEmpty()
but that returns a static list of tables (without querying the schema in the database).
I could write raw SQL to get the table list, but that would be specific to the database engine. Is there a generic alternative in jOOQ?
You cannot use:
db.Public.PUBLIC.getTables().isEmpty()
Because generated meta information is not connected to the database. Instead, you may want to take a look at DSLContext.meta(). In your case, you'd simply write:
DSL.using(configuration).meta().getTables().isEmpty();
If you run this test very often, that's of course not a very performant way of checking if there are any tables, as it will fetch all tables into memory just to run an isEmpty() check. I suggest issuing an actual query instead:
int numberOfTables =
DSL.using(configuration)
.select(count())
.from("information_schema.tables")
.where("table_schema = 'PUBLIC'")
.fetchOne(0, int.class);
A future jOOQ version (after 3.11) will be able to offer you actual object existence predicates that can be used in SQL or elsewhere:
https://github.com/jOOQ/jOOQ/issues/8038

Possible in JDBC / MySQL to retrieve updated rows?

preparedStatement.executeUpdate()
Returns the number of rows updated. To my research so far it's not possible to do an update-query in which you would retrieve the updated rows, but this seems like such a basic feature that I'm clearly missing something. How to accomplish this?
Per first comment on question this is simply not possible in MySQL. PostgreSQL supports UPDATE...RETURNING as this feature.
If you use executeQuery instead of executeUpdate, you get a resultset back.
Then, change your stored procedure to be a function, and return the changed rows in a select at the end of the function. AFAIK, you cannot return data from a procedure in MySQL (as opposed to e.g. Microsoft SQL server).
EDIT: The suggestion struck out above is not possible. The JDBC specification does not allow updates in query statements (see the answer for this one: http://bugs.mysql.com/bug.php?id=692).
BUT, if you know the WHERE clause of the rows you are about to update, you can always select them first, to get the primary keys, perform the update, and then perform a select on them afterwards. Then you get the changed rows.
when you fire preparedStatement.executeUpdate() you already have the row identifiers using which you can uniquely identify the rows you want updated- you need to use the same identifiers to do a query and fetch the updated rows. you can not accomplish update and retrieval in one shot using JDBC apis.

how to check database table permissions in java? (DataBase independently)

Does anyone know a way (in java) to check permissions to a specific table for a user? It has to work on the most Databases. SELECT right is simple to check (just trying to execute a simple SELECT statement), but how to check INSERT permission?
You can use the DatabaseMetaData to get this information. It should work in most cases. However, it might be inaccurate in special cases, if the privileges can not be represented in this abstract way:
DatabaseMetaData metaData connection.getMetaData();
metaData.getTablePrivileges();
metaData.getColumnPrivileges();
though not a direct solution but the only option that comes to my mind is to use TRY CATCH blocks, issue an INSERT statement and then checking the error message in java.sql.SQLException object returned in case of exception.

Problem facing while inserting data into dynamically created column of table

I am dynamically adding column to table in db through code using alter table query.
But i am facing problem wen i am trying to insert values in that column. it throws an exception column does not exists.
And wen i clean and rebuild my project through netbeans it works fine.
I am using java and mysql as databse .
Is there any body who know the solution for this problem.
Following is my alter table query Code
String alterTableQuery ="alter table `test` add `abc` varchar(50) NOT NULL default ''";
stmt = conn.prepareStatement(alterTableQuery);
boolean val = stmt.execute();
And I am trying to insert data using following code.
String sqlQuery = "insert into `test` (`id`,`abc`) values (?)" ;
stmt = conn.prepareStatement(sqlQuery);
boolean val = stmt.execute();
You might also rethink your design. In general it is a poor practice for the user interface to add columns to tables. Perhaps you need a more normalized design. Database structural changes should not come from the user. You could create a real mess if different users were making changes at the same time. Additionally users should not have the security rights to add columns. This is a major risk for your system.
I dont know about Java but in .net after performing a change on a table you need to call dataAdapter.AcceptChanges(); which essentially commits the change to the table.
In your codedo you need to make a similar call after you have added the column to the table,for the insert to be able to work.
This may be because Data Description Language (DDL) is often executed outside of transactions. Perhaps a commit/rollback, or even reconnect would sort the problem. Just a guess.

Access to auto increment identity field after SQL insert in Java

Any advice on how to read auto-incrementing identity field assigned to newly created record from call through java.sql.Statement.executeUpdate?
I know how to do this in SQL for several DB platforms, but would like to know what database independent interfaces exist in java.sql to do this, and any input on people's experience with this across DB platforms.
The following snibblet of code should do ya':
PreparedStatement stmt = conn.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS);
// ...
ResultSet res = stmt.getGeneratedKeys();
while (res.next())
System.out.println("Generated key: " + res.getInt(1));
This is known to work on the following databases
Derby
MySQL
SQL Server
For databases where it doesn't work (HSQLDB, Oracle, PostgreSQL, etc), you will need to futz with database-specific tricks. For example, on PostgreSQL you would make a call to SELECT NEXTVAL(...) for the sequence in question.
Note that the parameters for executeUpdate(...) are analogous.
ResultSet keys = statement.getGeneratedKeys();
Later, just iterate over ResultSet.
I've always had to make a second call using query after the insert.
You could use an ORM like hibernate. I think it does this stuff for you.
#ScArcher2 : I agree, Hibernate needs to make a second call to get the newly generated identity UNLESS an advanced generator strategy is used (sequence, hilo...)
#ScArcher2
Making a second call is extremely dangerous. The process of INSERTing and selecting the resultant auto-generated keys must be atomic, otherwise you may receive inconsistent results on the key select. Consider two asynchronous INSERTs where they both complete before either has a chance to select the generated keys. Which process gets which list of keys? Most cross-database ORMs have to do annoying things like in-process thread locking in order to keep results deterministic. This is not something you want to do by hand, especially if you are using a database which does support atomic generated key retrieval (HSQLDB is the only one I know of which does not).

Categories

Resources