I am trying to make a variable Table name through Java.
My code is :
public void createTable(String tableName){
try {
Statement stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE '"+tableName+"'" +
"(id INTEGER not NULL, " +
" username VARCHAR(255), " +
" pass VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))");
}
catch (SQLException e){
e.printStackTrace();
}
}
It gives me a syntax error saying:
Incorrect syntax near 'VariableTableNameIChose'.
Does anyone have any ideas?
It could be one of 2 things or the combination of both.
Maybe the single quotes around the table name are not valid in your database. So do like this:
stmt.executeUpdate("CREATE TABLE "+tableName+" " +
"(id INTEGER not NULL, " +
" username VARCHAR(255), " +
" pass VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))");
Or maybe you need a spaces between the table name and the ( following after:
Statement stmt = con.createStatement();
// v this one was missing
stmt.executeUpdate("CREATE TABLE '"+tableName+"' " +
"(id INTEGER not NULL, " +
" username VARCHAR(255), " +
" pass VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))");
The table name is an identifier. Identifiers do not use single quotes (in standard SQL).
"CREATE TABLE '"+tableName+"' "
Will result in
CREATE TABLE 'foobar'
which is invalid SQL. You need to remove the single quotes:
"CREATE TABLE "+tableName+" " + ...
As the table name is apparently a user input, you might actually want to use quoted identifiers (although this is in general a bad idea). Identifiers are quoted using double quotes in the SQL standard:
"CREATE TABLE \""+tableName+"\" " + ...
Related
I'm using JDBC in eclipse IDE , i want to put two foreign keys in my table 3 , one is referencing to the primary key in table 1 and one is referencing to the primary key in table 2. When i only put one foreign key constrains for any referencing table1 or table 2 , it works fine but when i include two it gives me sql exception as stated below:
java.sql.SQLSyntaxErrorException: 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 'foreign key(T2) references
Table2(T2) )' at line 1
String createString =
// TABLE 1
"CREATE TABLE " + this.tableName + " ( " +
"T1 varchar(50) NOT NULL PRIMARY KEY )";
// TABLE 2
"CREATE TABLE " + this.tableName + " ( " +`enter code here`
"T2 varchar(50) NOT NULL PRIMARY KEY )";
// TABLE 3
"CREATE TABLE " + this.tableName + " ( " +
"T1 varchar(50) " +
"T2 varchar(50) " +
"foreign key(T1) references Table1 (T1)" +
"foreign key(T2) references Table2(T2) )";
First, this is actually a MySQL question, unrelated to Java/JDBC. Secondly, and more importantly, you don't appear to be using the correct syntax, which would be...
CREATE TABLE TableName (
T1 varchar(50),
T2 varchar(50),
foreign key(T1) references Table1(T1),
foreign key(T2) references Table2(T2)
);
Formatted for your code, it would look like this:
String createString = "CREATE TABLE " + this.tableName + " ( " +
" T1 varchar(50)," +
" T2 varchar(50)," +
" foreign key(T1) references Table1(T1)," +
" foreign key(T2) references Table2(T2));";
You were missing commas after each item in the items list for your CREATE TABLE statement.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Essentially, I am creating football database software that uses MySQL and Java (via JDBC). I have created my database connection which works fine, but when I try to call it to another class it does not work. The getter is public and my Connection variable 'conn' is also public. I am getting nullpointers on the getter line of code when I use it in other classes, however, when I tested the getter it doesn't give me a nullpointer. Here are the two classes that I am testing - including the string of code giving me nullpointers:
CLASS 1:
package ns00790_footballproject;
import java.sql.*;
public class DatabaseConnection {
public Connection conn;
public DatabaseConnection() {
try{
String url = "jdbc:mysql://localhost:3306/?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
String user = "root";
String password = "";
// 1. Get a connection do database
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println("Connected ok");
// 2. Create a statement
Statement st = conn.createStatement();
st.execute("CREATE DATABASE IF NOT EXISTS FOOTBALL_LEAGUE;" );
st.execute("USE FOOTBALL_LEAGUE");
st.execute("CREATE TABLE TEAMS(" +
" teamID INT (10) NOT NULL AUTO_INCREMENT," +
" teamName VARCHAR (50)," +
" homeWins INT," +
" homeDraws INT," +
" homeLoss INT," +
" awayWins INT," +
" awayDraws INT," +
" awayLoss INT," +
" homeGoalsFor INT," +
" homeGoalsAgainst INT," +
" awayGoalsFor INT," +
" awayGoalsAgainst INT," +
" gamesPlayed INT," +
" PRIMARY KEY (teamID)" +
" );");
st.execute(" CREATE TABLE GAME(" +
" gameID INT (10) NOT NULL AUTO_INCREMENT," +
" homeTeam VARCHAR(50)," +
" teamID INT (10) NOT NULL," +
" awayTeam VARCHAR(50)," +
" homeScore INT," +
" awayScore INT," +
" PRIMARY KEY (gameID));");
st.execute("CREATE TABLE DETAILS(" +
" goalID INT NOT NULL AUTO_INCREMENT," +
" gameID INT (10) NOT NULL," +
" playerID INT (10)NOT NULL," +
" PRIMARY KEY (goalID));");
st.execute("CREATE TABLE PLAYERS(" +
" playerID INT (10)NOT NULL AUTO_INCREMENT," +
" teamID INT (10) NOT NULL," +
" name VARCHAR(50)," +
" goalsScored INT," +
" penaltyCards INT," +
" PRIMARY KEY (playerID));");
st.execute("ALTER TABLE game ADD INDEX (`teamID`)");
st.execute("ALTER TABLE `game` ADD FOREIGN KEY (`teamID`) REFERENCES `teams`(`teamID`) ON DELETE CASCADE ON UPDATE CASCADE;");
st.execute("ALTER TABLE DETAILS ADD INDEX (`playerID`)");
st.execute("ALTER TABLE `DETAILS` ADD FOREIGN KEY (`playerID`) REFERENCES `players`(`playerID`) ON DELETE CASCADE ON UPDATE CASCADE");
st.execute("ALTER TABLE DETAILS ADD INDEX (`gameID`)");
st.execute("ALTER TABLE `DETAILS` ADD FOREIGN KEY (`gameID`) REFERENCES `game`(`gameID`) ON DELETE CASCADE ON UPDATE CASCADE");
st.execute("ALTER TABLE PLAYERS ADD INDEX (`teamID`)");
st.execute("ALTER TABLE `PLAYERS` ADD FOREIGN KEY (`teamID`) REFERENCES `TEAMS` (`teamID`) ON DELETE CASCADE ON UPDATE CASCADE");
}
catch(Exception exc) {
exc.printStackTrace();
}
}
public Connection getConnection(){
return conn;
}
}
CLASS 2: (method that isnt working)
public void viewPlayerByTeam() {
try {
conn.getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery("SELECT * FROM PLAYERS");
rs.last();
System.out.println("Connected");
System.out.println(rs.getRow());
}catch(SQLException e){
System.out.println("SQL Error");
}
}
The output should be the number of rows currently in the table, which is 4. I am only getting null-pointer errors.
You are initializing wrong conn reference. There are two objects in your code when there should be one. Do not declare conn locally.
My question is very simple. I just want to know how to write a create Table statement for MySQL using Java statements where the name of the table is a string.
I know how to insert String values as values of the coloumns using Java. I tried it that way but could not do it. I will show you my code:
String table = "CREATE TABLE table_name'" +
"(SL. No INT not NULL AUTO_INCREMENT, " +
" NAME VARCHAR(100), " +
" YEAR INT not NULL, " +
" IMDB INT not NULL)";
Here instead of table_name I want to input a string variable. The variable name is s2.
Now the Insert into table value is as follows:
myStmt.executeUpdate("insert into l1(id,email,usname,pwd)value('"+(i)+"','"+s1+"','"+s2+"','"+s5+"')");
Here s1,s2,s5 are string values. But this method is not working for Create Table and it is showing syntax error. What is the correct code?
You should remove additional ' sign and change name for SL. No column to somethin else so it looks like
String table = "CREATE TABLE table_name" +
"(slno INT not NULL AUTO_INCREMENT, " +
" NAME VARCHAR(100), " +
" YEAR INT not NULL, " +
" IMDB INT not NULL)"
If your table string is correct you can replace table_name with new name for each table with replace method on string or just use function
public static String getCreateTableQuery(String tableName) {
String table = "CREATE TABLE table_name" +
"(slno INT not NULL AUTO_INCREMENT, " +
" NAME VARCHAR(100), " +
" YEAR INT not NULL, " +
" IMDB INT not NULL)";
String createTableWithNewNameQuery = table.replaceFirst("table_name'", tableName);
return createTableWithNewNameQuery;
}
I can't create a table in the database (mySQL), using preparedStatement and try to enter name of future table with preparedStatement.setInteger():
static String queryCreateTable = "CREATE TABLE ?" +
"(ID INTEGER not NULL ," +
"BRAND VARCHAR(40)," +
"MODEL VARCHAR(40)," +
"YEAR INTEGER not NULL," +
"NOVELTY BINARY," +
"PRIMARY KEY ( ID ))";
And then I try to construct and call the statement after inputing name of table by user:
newNameOfTable = JOptionPane.showInputDialog("Connected for saving data. " +
"Input name of new table:");
pStatement = connection.prepareStatement(queryCreateTable);
pStatement.setString(1, newNameOfTable);
pStatement.executeUpdate();
It works well if I try to execute it without entering name (like a constant string: "CREATE TABLE newtable (...)" but I need to enter name..
You will have to format the string after reading the table name, something like:
static String queryCreateTable = "CREATE TABLE {0}" +
"(ID INTEGER not NULL ," +
"BRAND VARCHAR(40)," +
"MODEL VARCHAR(40)," +
"YEAR INTEGER not NULL," +
"NOVELTY BINARY," +
"PRIMARY KEY ( ID ))";
then create like:
newNameOfTable = JOptionPane.showInputDialog("Connected for saving data. " +
"Input name of new table:");
statement = connection.createStatement();
statement.execute(MessageFormat.format(queryCreateTable, newNameOfTable));
newNameOfTable = JOptionPane.showInputDialog("Connected for saving data. " +
"Input name of new table:");
static String queryCreateTable = "CREATE TABLE " + newNameOfTable +
"(ID INTEGER not NULL ," +
"BRAND VARCHAR(40)," +
"MODEL VARCHAR(40)," +
"YEAR INTEGER not NULL," +
"NOVELTY BINARY," +
"PRIMARY KEY ( ID ))";
pStatement = connection.prepareStatement(queryCreateTable);
pStatement.executeUpdate();
PreparedStatement example:
http://tutorials.jenkov.com/jdbc/preparedstatement.html
I am new to Java and MYSql in fact using this combination first time and facing real trouble. I want to insert few records in a table but unable to do so. Following are the fields and datatype in the table named tbl_cdr in MySql.
**Field** **Type**
DATEANDTIME datetime NULL
VALUE1 int(50) NULL
VALUE2 varchar(50) NULL
VALUE3 varchar(50) NULL
VALUE4 varchar(50) NULL
VALUE5 varchar(50) NULL
The record I want to insert contains following values
2014-05-19 02:37:18, 405, MGW190514023718eab4, 923016313475, IN, ALERTSC
I am using following query and statements to Insert record in table
sqlQuery = "INSERT INTO tbl_cdr (DATEANDTIME,VALUE1,VALUE2,VALUE3,VALUE4,VALUE5)" + "VALUES ("+ forDateAndTime.format(date) + ", " + columnsList.get(1) + ", " + columnsList.get(2) + ", " + columnsList.get(3) + ", " + columnsList.get(4) + ", " + columnsList.get(5) + ")";
try
{
Statement qryStatement = conn.createStatement();
qryStatement.executeUpdate(sqlQuery);
qryStatement.close();
} catch (SQLException ex)
{
Logger.getLogger(CdrProject.class.getName()).log(Level.SEVERE, null, ex);
}
But when I reach the statement qryStatement.executeUpdate(sqlQuery); exception is thrown as:
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 '02:37:18, 405, MGW190514023718eab4,
923016313475, IN, ALERTSC)' at line 1
value2 ,value3 ,value4 and value 5 are varchars so it should be written within ''.
Do like this
sqlQuery = "INSERT INTO tbl_cdr (DATEANDTIME,VALUE1,VALUE2,VALUE3,VALUE4,VALUE5)" + "VALUES ("+ forDateAndTime.format(date) + ", " + columnsList.get(1) + ", '" + columnsList.get(2) + "',' " + columnsList.get(3) + "',' " + columnsList.get(4) + "',' " + columnsList.get(5) + "')";
You're inserting the date incorrectly. MySQL allows you to insert a string literal or a number.
You're trying to use 02:37:18 as a number, when really you should be using it as a string literal: '02:37:18'
Here is the MySql Reference describing this.
You're also not treating your varchars as strings either, they should be enclosed with quotes.