Java database help - java

Working my way through a chapter of study and I have been given code where there is two databases made, I have compiled the code and it works. I have no tried to tweek the code so its only one database, when it comes to the selecting the information and displaying it i am just getting a blank no output from it, where have i went wrong im guessing its somewhere in the selection of information from the DB?
Thanks
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
public class FootballTeamDataBase
{
Connection connection;
Statement statement;
ResultSet results;
public FootballTeamDataBase()
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch (ClassNotFoundException cnfe)
{
System.err.println("Derby driver not found.");
}
try
{
// What drivers are there?
System.out.println("Available drivers:");
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements())
{
System.out.println(drivers.nextElement());
}
System.out.println();
connection = DriverManager.getConnection
("jdbc:derby://localhost:1527/MusicShop;create=true;user=admin;pass=admin");
statement = connection.createStatement();
try
{
statement.execute("drop table FootballTeam");
}
catch (SQLException e)
{
System.out.println("Table did not previously exist " + e);
}
// Now create the table.
statement.execute("create table " +
"FOOTBALLTEAM(" +
"ID varchar(12) primary key not null, " +
"POSITION varchar(24), " +
"NAME varchar(24),") ;
}
catch (SQLException sqle)
{
System.err.println("Problem:" + sqle);
}
}
public void addData()
{
try
{
statement.execute("insert into FOOTBALLTEAM values " +
"('1',Keeper','Dale'");
statement.execute("insert into FOOTBALLTEAM values " +
"('2',Defender','Lewis'");
statement.execute("insert into FOOTBALLTEAM values " +
"('3','MIDFIELD','Jones'");
}
catch (SQLException sqle)
{
System.err.println("Problem populating data:" + sqle);
}
}
public void showTeam()
{
try
{
// check the contents of the table
System.out.println("DB contents:");
// select all records
statement.execute("select * from FOOTBALLTEAM");
ResultSet results = statement.getResultSet();
while (results.next())
{
System.out.println(results.getString("ID") + " " + results.getString("POSITION") +
" = " + results.getString("NAME") );
}
}
catch (SQLException e)
{
// nothing wrong
}
}
}

Looking at these lines, your SQL statements are malformed:
statement.execute("insert into FOOTBALLTEAM values " +
"('1',Keeper','Dale'");
statement.execute("insert into FOOTBALLTEAM values " +
"('2',Defender','Lewis'");
statement.execute("insert into FOOTBALLTEAM values " +
"('3','MIDFIELD','Jones'");
Note that the SQL statements contain an opening ( but no closing ). Change it like this:
statement.execute("insert into FOOTBALLTEAM values " +
"('1',Keeper','Dale')");
statement.execute("insert into FOOTBALLTEAM values " +
"('2',Defender','Lewis')");
statement.execute("insert into FOOTBALLTEAM values " +
"('3','MIDFIELD','Jones')");
Likewise here, this does not look like a complete SQL statement:
// Now create the table.
statement.execute("create table " +
"FOOTBALLTEAM(" +
"ID varchar(12) primary key not null, " +
"POSITION varchar(24), " +
"NAME varchar(24),") ;

Perhaps you have not committed the data? connection.setAutoCommit(true), or, begin and end the transaction: JDBC Transactions

Related

MySQL checking if a entry is set

Im trying to check if a entry is set, so for example in a row with: user, password, birth
I check if in column user f.e. "mxrlin" is
For that im using that code in my Main Class:
if(!mySQL.isSet(tableName, "houseNumber", houseNumberStr)){
System.out.println(house.getHouseNumber() + " not set yet");
inserts.add(new BetterMySQL.KeyValue("houseNumber", houseNumberStr));
mySQL.insertEntry(tableName, inserts);
}else {
System.out.println(house.getHouseNumber() + " set -> updating");
mySQL.update(tableName, inserts, "houseNumber", houseNumberStr);
}
And the mySQL.isSet() method looks like this:
public boolean isSet(String tableName, String key, String value){
Check.checkNotEmpty(tableName);
Check.checkNotEmpty(key);
Check.checkNotEmpty(value);
ResultSet resultSet = MySQL.getResultSetPrepareStatement(connection, "SELECT * FROM " + tableName + " WHERE ?=?", Arrays.asList(key, value));
try {
if(resultSet.next()){
return resultSet.getObject(value) != null;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
But with this code it always debugs me "house.getHouseNumber() + " not set yet", so the Class doesnt find the entry that is set
You can't bind a parameter to a column name. The key in this case will be treated as a string literal in SQL.
Assuming a method call like this:
mySQL.isSet("houses", "houseNumber", "2335")
this code:
ResultSet resultSet = MySQL.getResultSetPrepareStatement(connection, "SELECT * FROM " + tableName + " WHERE ?=?", Arrays.asList(key, value));
Will generate a SQL statement equivalent to
SELECT * FROM houses WHERE 'houseNumber'='2335'
Of course, the string 'houseNumber' will never equal the string '2335', so no results will be returned.
You'll need to substitute key into the SQL string, just like tableName already is:
ResultSet resultSet = MySQL.getResultSetPrepareStatement(connection, "SELECT * FROM " + tableName + " WHERE " + key + "=?", Arrays.asList(value));

How can I fix syntax erroor "("?

Now I use postgreSQL and make stockmanagement program.
While I make table, the error has occured.
My Code like this!
import java.sql.Connection;
import java.sql.Statement;
public class Create_Table {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ConnectDB obj_ConnectDB = new ConnectDB();
connection = obj_ConnectDB.get_connection();
try {
String query = "CREATE TABLE IF NOT EXISTS stockmanagement ("
+ "ID SERIAL primary key, "
+ "Name varchar(20), "
+ "Unit_price numeric(15,1), "
+ "Qty INT(20),"
+ "Imported_Date Date,"
+ ")";
statement = connection.createStatement();
statement.executeUpdate(query);
System.out.println("finished");
} catch (Exception e) {
e.printStackTrace();
}
}
}
And the contents of error are as follows.
error : syntax error, "("
How can I fix this error?
If you know this solution, can you teach me?
You have two errors in the string.
Extra comma at the end
INT(20) is not legal
This should work
String query = "CREATE TABLE IF NOT EXISTS stockmanagement ("
+ "ID SERIAL primary key, "
+ "Name varchar(20), "
+ "Unit_price numeric(15,1), "
+ "Qty INT,"
+ "Imported_Date Date"
+ ")";

Simple JDBC SQL Query returns an empty ResultSet

I have been trying to get a plugin I am working on to talk to my SQL database, creating tabels, and adding rows seems to work fine but simple SELECT queries are returning an empty ResultSet. The relevant code is below.
queryL=
"SELECT RATING"
+ " FROM USERS"
+ " WHERE UUID = '"
+ UUID +"';";
queryG=
"SELECT RATING"
+ " FROM " + Constants.serverName
+ "_USERS"
+ " WHERE UUID = '"
+ UUID +"';";
try {
stmt=con.createStatement();
rs=stmt.executeQuery(queryL);
if (rs.next()){
r.setLocalRating(rs.getInt(1));
}else{
r.setLocalRating(0);
registerPlayer(UUID,false);
Dungeon.getPlugin(Dungeon.class).log("Player new to server");
}
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try{
stmt=con.createStatement();
rs=stmt.executeQuery(queryG);
if (rs.next()){
r.setGlobalRating(rs.getInt(1));
}else{
r.setGlobalRating(0);
registerPlayer(UUID,true);
Dungeon.getPlugin(Dungeon.class).log("Player new to network");
}
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
As you can see if the ResultSet is empty (player does not yet exist in my database) I call registerPlayer. Register player then throws a duplicate entry for primary key error, so I know the table and the row I am looking for exist.
The following code shows the update queries used inside the registerPlayer method.
if (global){
query=
"INSERT INTO"
//+ Constants.dbName + "."
+ " USERS"
+ " VALUES ('"
+ UUID + "', 0)";
}else{
query=
"INSERT INTO "
//+ Constants.dbName + "."
+ Constants.serverName
+ "_USERS "
+ "VALUES ('"
+ UUID + "', 0)";
}
Finally for completeness, the queries used for creating the tables
String userLocalTable=
"CREATE TABLE IF NOT EXISTS " //+ Constants.dbName + "."
+ Constants.serverName +
"_USERS " +
"(UUID varchar(36) NOT NULL, " +
"RATING int NOT NULL, " +
"PRIMARY KEY (UUID))";
String userGlobalTable=
"CREATE TABLE IF NOT EXISTS " + //Constants.dbName + "."
"USERS " +
"(UUID varchar(36) NOT NULL, " +
"RATING int NOT NULL, " +
"PRIMARY KEY (UUID))";
Any insight into my issue would be greatly appreciated, as far as I can tell the SELECT queries should not be returning empty ResultSets.
Thanks for the input, turns out it was something obvious staring me in the face, QueryL's and QueryG's respective queries needed to be swapped.

No such Table Sqlite JDBC

Yo guys. The problem I'm facing is pretty weird..
I am creating a table at first, then trying to put data on it, but for somereason something is ticking off. It says
[SQLITE_ERROR] SQL error or missing database (no such table: Name)
Aaand here's my basic code..
try{
Class.forName("org.sqlite.JDBC");
conni = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
stmt = conni.createStatement();
String sql = "CREATE TABLE " + project.getText() + " (Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , Name TEXT, One TEXT, Two TEXT)";
stmt.executeUpdate(sql);
stmt.close();
conni.close();
}catch (Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
try{
Class.forName("org.sqlite.JDBC");
conni = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
String query1 = "insert into Name (Name) values(?)";
PreparedStatement pst = conni.prepareStatement(query1);
pst.setString(1, project.getText());
pst.execute();
pst.close();
conni.close();
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
try{
Class.forName("org.sqlite.JDBC");
conni = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
String query1 = "insert into " + project.getText() + "(Name, One, Two) values(?,?,?)";
PreparedStatement pst = conni.prepareStatement(query1);
pst.setString(1, project.getText());
pst.setString(2, textField_one.getText());
pst.setString(3, textFieldtwo.getText());
pst.execute();
pst.close();
conni.close();
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
JOptionPane.showMessageDialog(null, "Thank you");
Thank you for the help! I really can understand... I guess the table is not being created at all, but it actually worked once. So It gets me even more confused o.o
Name is a MySql reserved keyword. Rename the table to something else.
Please encase your fieldnames with " to escape them.
String sql = "CREATE TABLE \"" + project.getText() + "\" (\"Id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , \"Name\" TEXT, \"One\" TEXT, \"Two\" TEXT)";
String query1 = "insert into \"Name\" (\"Name\") values(?)";
String query1 = "insert into \"" + project.getText() + "\" (\"Name\", \"One\", \"Two\") values(?,?,?)";
Also... I'm assuming you've patched together these code snippets from various points in your code..
But i advice you to set up a SINGULAR database connection in your code and to reuse that connection throughout your application.
Something along the lines of:
public class MyApp {
public static Connection DB;
public void initDatabase() {
try {
MyApp.DB = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
}
catch(Exception ex) {
}
}
public static void main(String args[]) {
MyApp app = new MyApp();
app.initDatabase();
}
}

servlet init method fails to create mysql tables - why?

my java servlet init method fails to create mysql tables - I'd like to know why. When I log on to mysql directly and create the tables life is beautiful, when I delete the tables and run the servlet - no tables, servlet throws an exception (haven't quite dug that up yet).The code looks like this:
package ...;
import ... // quite a bit
#WebServlet("/MyClass")
public class MyClass extends HttpServlet {
public void init() throws ServletException {
try { Foo foo = Foo.getInstance();
foo.createTables();
} catch (Exception e) {
throw new ServletException("Error creating tables", e);
}
}
... // more MyClass stuff
}
//Foo is a singleton that looks like this:
package ...;
import ... // quite a bit
public class Foo {
public static final Foo INSTANCE = new Foo();
public static Foo getInstance() {
return INSTANCE;
}
... // more Foo stuff, then
public void createTables(){
try {
// first establish a connection
Connection connection = Foo.getInstance().getConnection(); // get connection est.
// est. connection to dbase - works well once the tables are set up
//Create a query.
Statement stmt = connection.createStatement();
String query = "CREATE TABLE IF NOT EXISTS survey (uuid_Survey VARCHAR(36) NOT NULL, "+
"top VARCHAR(40), " +
" likert VARCHAR(40), "+
" numerical VARCHAR(40), "+
" open VARCHAR(40), " +
" KEY ix_survey_uuid (uuid_Survey), "+
" PRIMARY KEY (uuid_Survey))";
ResultSet rs = stmt.executeQuery( query );
query = "CREATE TABLE IF NOT EXISTS result (" +
"uuid_Survey VARCHAR(36) NOT NULL, "+
"remoteAddress VARCHAR(15) NOT NULL, " +
"currentTime BIGINT NOT NULL, "+
" likert VARCHAR(40),"+
" numerical DOUBLE, " +
" open VARCHAR(40), "+
" PRIMARY KEY (uuid_Survey, remoteAddress, currentTime),"+
"FOREIGN KEY ix_survey_uuid (uuid_Survey) REFERENCES survey (uuid_Survey))" ;
rs = stmt.executeQuery( query );
connection.close();
} catch (Exception e) {
System.err.println("Error creating tables: " + e);
}
}
You cannot use stmt.executeQuery( query );
As the Doc says-
ResultSet#executeQuery(String sql) - This method executes the given SQL statement, which returns a single ResultSet object. where sql - an SQL statement to be sent to the database, typically a static SQL SELECT statement
You might want to use execute() instead
Like stmt.execute(query);
or
String query = "CREATE TABLE IF NOT EXISTS survey (uuid_Survey VARCHAR(36) NOT NULL,"+
"top VARCHAR(40), " +
" likert VARCHAR(40), "+
" numerical VARCHAR(40), "+
" open VARCHAR(40), " +
" KEY ix_survey_uuid (uuid_Survey), "+
" PRIMARY KEY (uuid_Survey))";
PreparedStatement statement = conn.prepareStatement(query);
int count = statement.executeUpdate();
if(count>=0){
System.out.println("Successfully created.");
}

Categories