I'm at a complete loss, I don't understand what is wrong here. I'm writing a Java program to take a few databases and put them into a mySQL database. I've got the JConnector in my build path:
Build path screenshot
try {
String driver = "com.mysql.cj.jdbc.Driver";
String address = "jdbc:mysql://localhost:3306/?user=root/Exercise";
Class.forName(driver);
con = DriverManager.getConnection(address, username, password);
System.out.println("Connection Success");
Statement st = con.createStatement();
int c =st.executeUpdate("CREATE TABLE test (Name VARCHAR(30))");
System.out.println("Table have been created.");
System.out.println(c+" Row(s) have been affected");
return con;
} catch (Exception e) { System.out.println(e);}
When I run this code, the output is:
Connection Success
java.sql.SQLException: No database selected
When I delete the "?user=root" part of the address, it will instead give me:
java.sql.SQLNonTransientConnectionException: Cannot load connection class because of underlying exception: com.mysql.cj.exceptions.WrongArgumentException: Malformed database URL, failed to parse the main URL sections.
This implies that, if I can't connect to a database, that it'll throw the exception, so apparently it is connecting, but then it's saying no database is selected despite that I'm literally connecting to it just a few lines back. In fact, the Statement line to the return line are code I took from another question's solution about this specific issue to test it, and their code seemed to be almost exactly the same as my own. What in the world am I doing wrong here?
Edit: I just tried running it again without the "?user=root" because of g00se's answer, and I somehow got A DIFFERENT error message than the one I already posted that I was getting.
java.sql.SQLSyntaxErrorException: Unknown database 'exercise'
EDIT 2:
I just had a thought, Eclipse is on an external harddrive, and I have no idea where the SQL database is stored, but could that be the issue? They're on different drives?
For unknown reasons, the exercise database (as well as others I had) went missing or were deleted. Thank you to g00se for suggesting I look at the databases and see what was actually there, readding it fixed the problem.
Related
I'm using MySQL 5.7 with Java in Eclipse, and the connection statement below code below is causing an error when I try to connect:
try
{
//1. Get a connection to database
jdbc:mysql://localhost:3306/databaseName?autoReconnect=true;useSSL=false;
// 2. Create a statement
Statement myStmt=myConn.createStatement();
// 3. Execute SQL query
ResultSet myRs=myStmt.executeQuery("select * from employee");
//4. Process the result set
while(myRs.next())
{
System.out.println(myRs.getString("last_name")+","+myRs.getString("first_name"));
}
}
catch(Exception exc){
exc.printStackTrace();
}
First things first.
Code will only be used to validate the error. So you must paste the error fired by your program.
Since we don't have enough information to the problem, I will just cover basic troubleshooting.
Basic trouble shooting:
Do you have the driver? if not, you can download it here.
Next, Do you have the driver on your project class path? If not yet, you must add it. see how here
Did you load the driver to the program? if not, Class.forName("com.mysql.jdbc.Driver"); // Load Driver like that before doing anything.
Did you establish the connection? if not, Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/DATABASE","USERNAME","PASSWORD");//3306 or port number depends on you config, same with DATABASE, USERNAME, PASSWORD
After the connection were established, so you should create a statement object like Statement s = con.createStatement(); // Create Statement. This will be used to execute sql commands.
finally, you can execute the commands like s.execute("select * from employee"); // Execute Query NOTE that s here is the variable created on number 5.
If all of the above were properly done but still gets an error, check if your have the database server running. In you case, mysql. Make sure there were not other installation of mysql prior to your current mysql. Sometimes, it will mess up your database. Troubleshooting your mysql, see mysql official doc here
While possible error is the datatype of mysql to your java code or getting a column that does not exist on your query or worse the column does not exist on your table.
Hope that help you and other who needs it.
I am getting the above error when trying to do an insert(or select) to a SQLite file from Java in Netbeans. I have created the db file manually from SQLite Database Browser and put it in the source package. Below is the code and logs:
public void DBInsertServerConfig(ServerConfig serverconfig) throws SQLException {
Connection conn = DBConnect();
Statement statement = null;
conn.setAutoCommit(false);
statement = conn.createStatement();
String sql = "INSERT INTO serverconfig(ip,port,db_name,db_user,password,fcm_server_key) " +
"VALUES (?,?,?,?,?,?)"; //
try{
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setString(1,serverconfig.getIp());
pstm.setString(2,serverconfig.getPort());
pstm.setString(3,serverconfig.getDb_name());
pstm.setString(4,serverconfig.getDb_user());
pstm.setString(5,serverconfig.getPassword());
pstm.setString(6,serverconfig.getFcm_server_key());
//statement.execute(sql);
pstm.executeUpdate();
statement.close();
conn.commit();
conn.close();
The database is opened correctly but it seems it doesn't find the table although it exist.
compile:run:
Opened database successfully
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: serverconfig)
BUILD SUCCESSFUL (total time: 9 seconds)
Attached is a screenshot of the db file from SQLite Database Browser :
I have seen and tried other posts like in here but I didn't get a solution.
Can anyone help me figuring out this?
I found the answer and I am posting if anyone run into the same problem/confusion.
I had put my db file under the src package while the url path was pointing into the project root folder(outside src). An empty db file was created by netbeans, and of course it hadn't any table in it. That's what happen when you follow tutorials that haven't been tested by their own creators. :D
The example that I used was
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Tolga\\Documents\\NetBeansProjects\\dpmlzmtkb\\depom.sqlite");
Which is wrong.
I changed depom.SQLite to depom.db and it worked. So as I understand if the path is correct NetBeans creating another empty SQLite database to the given path.
Please use the absolute path,like(on my Ubuntu)
private static String url ="jdbc:sqlite:/home/yourname/study/eclipse/hk/ss.db";
At first i get same error like yours,
i can link sql in ordinary class,but in the servlet/jsp can't
I have read the topics in Stackoverflow about this problem, but I really haven't a solution yet.
My problem is sending a String or Clob as an XML parameter in a Stored Procedure in SQL Server 2008. I'm using jTDS to connect it. I've read that I have to set the "ARITHABORT" to ON, but I really don't know where I can do it.
Maybe in my own session in JAVA or in DB too... Please help!! (And sorry for my very very bad english)
Ok! Here is the method that is giving me the error:
private static final String PR_SV_MUDA_STATUS_EVENTO_CONCLUIDO = "{CALL PR_SV_MUDA_STATUS_EVENTO_CONCLUIDO(?, ?, ?, ?)}";
public String modificaStatus(Connection connection, Integer eventoRobo, String path) throws SQLException {
Connection conn = null;
conn = GenericHibernateDAO.criaConexao();
CallableStatement cs2 = conn.prepareCall(PR_SV_MUDA_STATUS_EVENTO_CONCLUIDO);
cs2.setInt(1, eventoRobo);
cs2.setString(2, null);
cs2.setString(3, null);
cs2.setString(4, path);
cs2.execute();
conn.close();
return null;
}
I believe this is the query
SET ARITHABORT ON;
This needs to be run before your stored procedure. Either you can run it soon after getting the connection.
Once the processing is done, you may want to run the query below.
SET ARITHABORT OFF;
These queries can be run using additional statements in your java program.
I ran into this problem today and got it solved. I created a filtered index on a column in sql server 2008 r2, but would get this error when inserting. Saw this question wasn't completely answered since it might be tedious to always turn arithabort on in every insert. I found a blog that showed it was the database compatibility level that was the issue. Changed the compatibility level from 80 (2000) to 100 (2008) and the issue was solved. not sure if changing the compatibility level to 90 would solve this or not, but worth a try.
SQL Server compatibility levels and command to change here. http://msdn.microsoft.com/en-us/library/bb510680.aspx
If this doesn't work or you can't change the compatibility mode there is another workaround by adding a trigger in the blog I was talking about here http://chrismay.org/2013/05/23/interesting-problem-with-sql-server-arithabort-filtered-indexes-calculated-columns-and-compatibility-mode-of-80/
Note that this change was done on a test database, and all applications should be tested before making a change like this in production. Make sure this is ok with your DBA before changing too.
what I'm trying to do is get a ResultSet from a SQL statement from which then I can derive certain values. What I seem to be having troubles with is the preparing of the prepared statement which occurs at this line.
String sql = "SELECT " + dataState + " FROM " + table + whereState + ";";
java.sql.PreparedStatement prep = conn.prepareStatement(sql); // Error here
I've already checked that the variable conn is not null. All the values in the statement are not null and the stack trace shows this.
java.lang.NullPointerException
at org.sqlite.PrepStmt.(PrepStmt.java:37)
at org.sqlite.Conn.prepareStatement(Conn.java:231)
at org.sqlite.Conn.prepareStatement(Conn.java:224)
at org.sqlite.Conn.prepareStatement(Conn.java:213)
at org.utilities.storagemethods.SQLiteMethod.load(SQLiteMethod.java:223)
at org.utilities.DataManager.load(DataManager.java:97)
at org.utilities.Test.main(Test.java:21)
A print of the sql statement shows that it gives this.
SELECT testString, testBool, testObj FROM testTable WHERE testInt=?;
You can ascertain the values from the given string.
What I can't figure out is what I'm doing wrong to cause this, if you're curious about what sqlite system I'm using, you can find the home page here: http://www.zentus.com/sqlitejdbc/
Thanks in advance for any help on this. I'm completely stumped.
Note: In an attempt to save resources, I was caching my Connection's, and re-using them later. When I try re-getting the connection, it works perfectly. Is there a way I can cache them or do I need to load them every time I want to use it?
I was getting this error, and it was caused because I had closed the connection. The connection wasn't null, it was just closed. ARRRGGG! Like the OP hinted at, I had started with the sample code at Zentus (Xerial now, since Zentus seems to have shut down). The sample code has a finally block where he closes the connection. Once I took out the finally block, my error disappeared. Just remember to close the connection before you exit the program.
To see if you have the same problem, right before the line that gives the error, try adding
System.out.println("isClosed = " + conn.isClosed());
If not wrong, I think it is because of ';' inside your SQL statement. Please remove and try again ?
Regards,
Code Behind
I am new to using Derby and databses in eclipse, and I have become a tad lost and in need to a bit of help. I have established a database connection, created a new database, and a new schema, within which I have some tables containing some test data. I don't have any problem with the sql queries to select the relevant data. The problem I have is getting to a point where I can use queries. I am trying to create a class which connects to the database, and for testing purposes, uses a simple query to select some data. This is what I have so far:
public void getExerciseInfo() {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
connect = DriverManager.getConnection("jdbc:derby://localhost/c:/TestDatabase");
PreparedStatement statement = connect.prepareStatement("SELECT * from TESTSCHEMA.TESTTABLE");
resultSet = statement.executeQuery();
while (resultSet.next()) {
String name= resultSet.getString("NAME");
String type = resultSet.getString("TYPE");
System.out.println(name);
System.out.println(type);
}
} catch (Exception e) {
} finally {
close();
}
}
All I am trying to do is output the data in the table to the console, but I cant even do this simple task :( Im guessing my connection url is invalid, is it supposed to be the file path to the database folder in my eclipse workspace?
Anyhow, I am very lost, and any help would be greatly appreciated.
Did you take a look over: http://db.apache.org/derby/integrate/plugin_help/derby_app.html ? You seem to be using the network server but your db URL is wrong.
If you are not running the Derby server, you can establish an embedded database connection or use an EmbeddedDataSource, shown here.