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"
+ ")";
Related
I'm trying to create a table with a list of names in it. This outputs:
"Failed to create table_name"
It was working before, I'm using Netbeans IDE with SQLite 3.7.2. I've also tried executing statements on the database which works fine. But it won't work through the Java code below
class DatabaseHelper{
public void addToDb(String tbname, List<String> name){
try {
String url = "jdbc:sqlite:D:/names.db";
Class.forName("org.sqlite.JDBC");
try(Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();){
stmt.execute("CREATE TABLE IF NOT EXISTS " + tbname + "(id integer PRIMARY KEY AUTOINCREMENT,"
+ "name text NOT NULL)");
name.forEach((s) -> {
try{
stmt.execute("INSERT INTO " + tbname + "(name) VALUES('" + s + "')");
}catch(SQLException e){
e.printStackTrace();
}
});
System.out.println("Finished");
}catch(SQLException e){
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
EDIT : It does works, only takes to refresh it. No actual problems it seems
Try to create your table with a database name like this :
String query = "CREATE TABLE IF NOT EXISTS databasename." + tbname +
" (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL)";
If your database already contain schema then create your table with schema name like this :
CREATE TABLE [IF NOT EXISTS] [schema_name].table_name (
so :
String query = "CREATE TABLE IF NOT EXISTS sch_name." + tbname +
" (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL)";
You can learn more here : SQLite Create Table
Ooops this is logic
This error is logic it return false all the time, if you try st.executeUpdate(q) and your query is success it will return 0 because CREATE TABLE does not return any thing for that you get negative result all the time, not like Insert or Update it return a result when you execute your statement, so i suggest to change your code to this :
boolean created;
try {
q = "CREATE TABLE ...";
Statement st = connection.createStatement();
//you can use
System.out.println(st.executeUpdate(q));
//or
System.out.println(st.execute(q));
created = true;
} catch (SQLException e) {
created = false;
}
//now you can check if your table is created or not
if(created){
System.out.println("Table created with sucess");
}else{
System.out.println("Faild to create table");
}
Hope this work with you.
if(stmt.execute("CREATE TABLE IF NOT EXISTS " + tbname + ";"+"CREATE TABLE "+ tbname + "(id integer PRIMARY KEY AUTOINCREMENT,"
+ "name text NOT NULL)"))
or can you give the exception that was raised
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.
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();
}
}
I am getting the following error when I try to create a table in an SQL database:
Failed to create table 'references'
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 'references(referenceID BIGINT NOT NULL AUTO_INCREMENT,
referenceText VARCHAR(255)'
Here is the code making the table:
public void createReferencesTable() {
System.out.println("Creating table '" + REFERENCE_TABLE + "'...");
Statement stmt = null;
try {
stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE " + REFERENCE_TABLE + "("
+ REFERENCE_ID + " BIGINT NOT NULL AUTO_INCREMENT,"
+ REFERENCE_TEXT + " VARCHAR(255),"
+ REFERENCE_TWEET + " BIGINT NOT NULL,"
+ "PRIMARY KEY (" + REFERENCE_ID + ")"
+ ")");
System.out.println("Table '" + REFERENCE_TABLE + "' created");
} catch (SQLException e) {
System.err.println("Failed to create table '" + REFERENCE_TABLE + "'");
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
And here are the declarations of the variables used:
public static final String REFERENCE_TABLE = "references";
public static final String REFERENCE_ID = "referenceID";
public static final String REFERENCE_TEXT = "referenceText";
public static final String REFERENCE_TWEET = "referenceTweet";
Also, I am creating two tables before this one that successfully work with basically the exact same syntax as this one, which is failing. Also, the MySQL server I am putting this databases into is fresh and just set-up, so there shouldn't be any configuration issues, as my program is connecting to the database successfully.
My question is: Why is this giving an error?
Notes: I have tried to do the reference ID line with an identity, but that did not make any difference. As I said before, the two functions each creating a table before this used exactly the same syntax, but gave no errors and successfully created their tables.
references is a reserved word in MySQL. Either use backticks to escape it or use another name.
stmt.executeUpdate("CREATE TABLE `" + REFERENCE_TABLE + "` ("
^-----------------------^-----------here
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