I have Created a database with this code Some days ago
sql = "Create Database if not exists My_Test_Project";
stmnt.executeUpdate(sql);
And Created Some tables at that time. Now I'm creating two new tables in it one with this query
sql = "CREATE TABLE if not exists My_Test_Project.Sales_Invoice_Help "
+ "(inv_help_id INTEGER,"
+ "item VARCHAR(255),"
+ "qty INTEGER,"
+ "rate DECIMAL (7, 2),"
+ "total DECIMAL (7, 2),"
+ "sale_inv_id INTEGER,"
+ " PRIMARY KEY (inv_help_id),FOREIGN KEY (sale_inv_id) REFERENCES Sales_Invoice (sale_inv_id))";
stmnt.executeUpdate(sql);
And when I Executed my program it throw Exception
SEVERE: null
java.sql.SQLException: No database selected
But at the same time this query executed successfully
sql = "CREATE TABLE if not exists My_Test_Project.Sales_Invoice "
+ "(sale_inv_id INTEGER not NULL, "
+ "date VARCHAR(255), "
+ "acc_name VARCHAR(255),"
+ "due_date VARCHAR(255),"
+ "customer_name VARCHAR(255),"
+ "receipt_no VARCHAR(255),"
+ "freight_charges INTEGER,"
+ "deliver_to VARCHAR(255),"
+ "deliver_date VARCHAR(255),"
+ "total INTEGER,"
+ "discount INTEGER,"
+ "g_total INTEGER ,"
+ " PRIMARY KEY (sale_inv_id))";
stmnt.executeUpdate(sql);
Note: Sales_Invoice table is first in sequence and in code too.
I do not know why its throwing exception. Can you please guide me.
I would believe in this line you will need to add the Database name:
REFERENCES Sales_Invoice (sale_inv_id)
So it should now be:
REFERENCES My_Test_Project.Sales_Invoice (sale_inv_id)
Related
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.
I have an app that allows users to store an int value for 50 different symptoms once per day. So in my SQLite db, my primary key is the symptom and the date (see below).
String CREATE_TABLE_SYMPTOM = "CREATE TABLE " + Symptom.TABLE + "("
+ Symptom.KEY_Symptom + " INTEGER NOT NULL , "
+ Symptom.KEY_date + " INTEGER NOT NULL , "
+ Symptom.KEY_level + " INTEGER , "
+ "PRIMARY KEY ( " + Symptom.KEY_Symptom + " , " + Symptom.KEY_date + " ))";
My table with have 50 entries per day which is alot.
Is there a more efficient way of breaking up this table so I won't have so many entries? I
I try to use HSQLDB embedded in program.
However, when I create table and insert data in the database, error occurs.
Following is part of error message.
java.sql.SQLSyntaxErrorException: unexpected token: MAR required: )
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.executeUpdate(Unknown Source)
It occurs when I insert some data in the database.
This is my CREATE statement.
stmt.execute("CREATE TABLE IF NOT EXISTS readability ( id INTEGER NOT NULL IDENTITY,"
+ "LOC INTEGER DEFAULT NULL, " + "numOfComments INTEGER DEFAULT NULL,"
+ "numOfBlankLines INTEGER DEFAULT NULL," + "numOfBitOperators INTEGER DEFAULT NULL,"
+ "readability double DEFAULT NULL," + "username varchar(255) DEFAULT NULL,"
+ "storedTime datetime DEFAULT NULL," + "methodname varchar(255) DEFAULT NULL,"
+ "classname varchar(255) DEFAULT NULL," + "patternrate double DEFAULT NULL,"
+ "maxNestedControl INTEGER DEFAULT NULL," + "programVolume double DEFAULT NULL,"
+ "entropy double DEFAULT NULL,"
+ "CONSTRAINT username FOREIGN KEY (username) REFERENCES user (username) ON DELETE NO ACTION ON UPDATE NO ACTION"
+ ");");
This is my INSERT statement.
stmt.executeUpdate(
"INSERT INTO readability (LOC, numOfComments, numOfBlankLines, numOfBitOperators,"
+ " readability, username, storedTime, methodname, classname, patternRate, maxNestedControl, programVolume, entropy) VALUES("
+ readability.getLOC() + ", " + readability.getNumOfComments() + ", "
+ readability.getNumOfBlankLines() + ", " + readability.getNumOfBitOperators() + ", "
+ readability.getReadability() + ", '" + readability.getUser().getUsername() + "', "
+ readability.getStoredTime() + ", '" + readability.getMethodName() + "', '"
+ readability.getClassName() + "', " + readability.getPatternRate() + ", "
+ readability.getMaxNestedControl() + ", " + readability.getProgramVolume() + ", "
+ readability.getEntropy() + ")",
Statement.RETURN_GENERATED_KEYS);
The object readability has all attributes used.
Do not concatenate values into a query string. Your code is vulnerable to SQL injection, and it is probably also the cause of the error. Use a prepared statement with parameter placeholders and set the values with the appropriate setters.
Your code would then become something like (leaving out a lot of columns for brevity):
try (PreparedStatement insert = connection.prepareStatement(
"insert into readability (LOC, username) values (?, ?)",
Statement.RETURN_GENERATED_KEYS)) {
insert.setInt(readability.getLOC();
insert.setString(readibility.getUser().getUsername());
insert.executeUpdate();
// handle generated keys...
}
You might also want to consider using an ORM like Hibernate.
I'm having an issue inputting information into a Sqlite database on the app I'm creating. I was using the help of the Cursor before. I am used to MySQL although clearly not 'used to' that well.
I am trying to add to the database from a file. I had this working before but it would be added with the Cursor. I was then told that in order to make it so I could add new information to the file and have the app ONLY add the new information into the database I should use INSERT OR IGNORE.
Is this the correct syntax? I currently am not having any information inserted for whatever reason...
ourDatabase.rawQuery("INSERT OR IGNORE INTO " + DATABASE_TABLE + " ("+KEY_CLASS+",
" + KEY_QUESTION+ ") VALUES ('" + qclass + "', '" + question + "');", null);
This is my database:
"CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_CLASS + " TEXT NOT NULL, " +
KEY_QUESTION + " TEXT NOT NULL UNIQUE);
Thanks for the help in advance!
Your query seems right but try the one below anyway
ContentValues insertValues = new ContentValues();
insertValues.put(KEY_CLASS, qclass);
insertValues.put(KEY_QUESTION, question);
yourDbName.insertWithOnConflict(DATABASE_TABLE, null, insertValues, SQLiteDatabase.CONFLICT_IGNORE);
KEY_QUESTION + " TEXT NOT NULL UNIQUE);";
I'm really struggling to sort some issues inserting time and dates into a table in my database that dosent seem to excist!.
I asked a question on the 'no such table' issue but didn't get an answer that sorted this issue and circumstances have changed.
Really hoping someone can help me as i cant go forward until i solve this.
Edit:
Does the logcat show im trying to insert before creating the table?
Heres my Logcat error:
01-20 23:38:24.128: E/Database(287): Error inserting app_time=00114200T000000Europe/Dublin(0,0,0,-1,0) app_alarm=false app_date=2013-01-24 app_name=gggg app_comments=a app_type=Business
01-20 23:38:24.128: E/Database(287): android.database.sqlite.SQLiteException: no such table: appointmentsTable: , while compiling: INSERT INTO appointmentsTable(app_time, app_alarm, app_date, app_name, app_comments, app_type) VALUES(?, ?, ?, ?, ?, ?);
Is it a case of this data cannot be inserted as there is no table? I have no idea why I cannot create a table. Im also confused as to why the values passed are '?'
Again here is my OnCreate method:
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_TEL + " TEXT NOT NULL, " +
KEY_EMAIL + " TEXT NOT NULL, " +
KEY_COMMENTS + " TEXT NOT NULL);"
);
db.execSQL("CREATE TABLE " + DATABASE_TABLEAPP + " (" +
KEY_ROWAPPID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAMEAPP + " TEXT NOT NULL, " +
KEY_TYPEAPP + " TEXT NOT NULL, " +
KEY_TIMEAPP + " TEXT NOT NULL, " +
KEY_DATEAPP + " TEXT NOT NULL, " +
KEY_COMMENTAPP + " TEXT NOT NULL, " +
KEY_ALARM + " BOOLEAN NOT NULL);"
);
}
My insertion method:
public void createAppointmentEntry(String nameApp, String typeApp, Time timeApp, Date dateApp ,String commentApp, Boolean onOrOff) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAMEAPP, nameApp);
cv.put(KEY_TYPEAPP, typeApp);
cv.put(KEY_TIMEAPP, timeApp.toString());
cv.put(KEY_DATEAPP, dateApp.toString());
cv.put(KEY_COMMENTAPP, commentApp);
cv.put(KEY_ALARM, onOrOff);
ourDatabase.insert(DATABASE_TABLEAPP, null, cv);
}
Do you see how you have your data types as " TEXT NOT NULL "? Try changing the "app_time" column to just " TEXT, " and increase the database version. Also, try downloading SQLite Viewer so that you can get a visual idea of what your db actually looks like and if the column exists.