First of all i would like to tell my apologies for asking this simple question. i am trying to connect sql-lite database table.I am using following code.
package derb;
import java.sql.*;
public class db {
public static void main(String[] args) throws Exception {
Class.forName("org.sqlite.JDBC");
Connection con=DriverManager.getConnection("jdbc:sqlite:/home/anand/MySQLiteDB.TEST","root","ROOT");
Statement st=con.createStatement();
String q="insert into CHECKING values(3)";
st.executeUpdate(q);
}
}
TEST is my database and i created one table called CHECKING in eclipse.but in above code gives me the error
Exception in thread "main" java.sql.SQLException: no such table: CHECKING
at org.sqlite.DB.throwex(DB.java:288)
at org.sqlite.NativeDB.prepare(Native Method)
at org.sqlite.DB.prepare(DB.java:114)
at org.sqlite.Stmt.executeUpdate(Stmt.java:102)
at derb.db.main(db.java:9)
I manually checked in the eclipse the table was available.but i don't know how to make the connection to that table.So any one can help me to fix this
Thank you
just now i come to know my mistake i just remove my db name from the connection string it works fine for me.
Connection con=DriverManager.getConnection("jdbc:sqlite:/home/anand/MySQLiteDB.TEST","root","ROOT");
changed to
Connection con=DriverManager.getConnection("jdbc:sqlite:/home/anand/MySQLiteDB","root","ROOT");
Related
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.
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 try
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import com.ibatis.common.jdbc.ScriptRunner;
public static void createDatabase() throws ClassNotFoundException, SQLException {
Class.forName("org.postgresql.Driver");
Connection connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/postgres", "postgres", "123456a#");
Statement stmt = connection.createStatement();
stmt.executeQuery("CREATE DATABASE IF NOT EXISTS foo");
stmt.executeQuery("USE foo");
connection.close();
}
and
public static void dropDatabase() throws ClassNotFoundException, SQLException {
Class.forName("org.postgresql.Driver");
Connection connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/", "postgres", "123456a#");
Statement statement = connection.createStatement();
statement.executeUpdate("DROP DATABASE foo");
connection.close();
}
but create, also drop method not success.
Error when call create method:
Exception in thread "main" org.postgresql.util.PSQLException: ERROR: syntax error at or near "NOT"
Position: 20
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2453)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2153)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:286)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:432)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:358)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:305)
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:291)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:269)
at org.postgresql.jdbc.PgStatement.executeQuery(PgStatement.java:236)
at com.nttdata.RunSqlScript.createDatabase(RunSqlScript.java:57)
at com.nttdata.RunSqlScript.main(RunSqlScript.java:27)
Error when call drop method:
Exception in thread "main" org.postgresql.util.PSQLException: ERROR: database "foo" is being accessed by other users
Detail: There is 1 other session using the database.
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2453)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2153)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:286)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:432)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:358)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:305)
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:291)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:269)
at org.postgresql.jdbc.PgStatement.executeUpdate(PgStatement.java:249)
at com.nttdata.RunSqlScript.dropDatabase(RunSqlScript.java:71)
at com.nttdata.RunSqlScript.main(RunSqlScript.java:28)
Firstly, the SQL syntax used while creating a database is incorrect in your question. The stack trace says it all about the incorrect syntax.
If you want to check whether the database exists or not, then you might have to do something like this in your Java code:
ResultSet rs = stmt.executeQuery("select datname from pg_database where datname like 'foo';");
not by the IF NOT EXISTS approach
Accessing this rs object will let you know whether the database exists or not. Then you can fire either your CREATE or DELETE database operations accordingly.
String databaseName = "";
if(rs.next()) {
databaseName = rs.getString("datname");
}
stmt.executeQuery("DROP DATABASE " + databaseName);
If a direct DROP DATABASE doesn't work (which I had faced a lot many times), you might consider using the dropdb utility or by one of the following approaches.
APPROACH-1
Use the following query to prevent future connections to your database(s):
REVOKE CONNECT ON DATABASE foo FROM public;
You can then terminate all connections to this database except your own:
SELECT pid, pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = current_database() AND pid <> pg_backend_pid();
Since that you have revoked the CONNECT rights to the corresponding database, no external auto-connect's will no longer be able to do so. You'll now be able to drop the database without any issues.
APPROACH-2:
This approach goes by the batch job way, where you can invoke this class from the corresponding jar:
Process batchProcess = Runtime.getRuntime().exec("C:/Program Files/PostgreSQL/9.5/bin/psql -h \"DB SERVER ADDRESS\" -U postgres -f C:/batch.sql");
batch.sql holds the SQL DROP DATABASE statements, which will be dropped when executed.
Hope this helps!
An option that you can try to use is to use a database migration tool like liquibase. There are couple of options that you can try from liquibase. One is to have an executable directly executed from the code (You first create a database change log file , with change sets. One of the commands in the change sets will be an executable
<changeSet author="exec-change-drop" id="drop-foo">
<executeCommand executable="<bat file with drop for PSQL or dropdb>"/>
</changeSet>
Another option that you can try is to write a sql and call it
<changeSet id="exec-change-drop2" author="drop-foo-2">
<sql>DROP DATABASE foo;</sql>
</changeSet>
You can then execute this from your code as follows
Class.forName("org.postgresql.Driver");
Connection connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/postgres", "postgres", "123456a#");
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
Liquibase liquibase = new liquibase.Liquibase("path/to/changelog.xml", new ClassLoaderResourceAccessor(), database);
liquibase.update(new Contexts(), new LabelExpression());
Note that your changeLogSchema may need to be in a different schema so that it executes seamlessly.
Additionally liquibase can be added with maven (this was the way it was supposed to be) and executed as well
I have a test suite of end-to-end tests. They are supposed to catch typos in SQL statements, bad table or column names (anything where DB schema and Java code disagree), or missing DB permissions. I don't want to rely on data in the database (too complicated to set up); this is just a basic test.
import java.sql.*;
import org.junit.Test;
public class TypoTest {
private Connection getConnection() throws Exception {
String connectionString = "jdbc:postgresql://127.0.0.1:5432/db";
String driverClassName = "org.postgresql.ds.PGConnectionPoolDataSource";
Class.forName(driverClassName).newInstance();
return DriverManager.getConnection(connectionString, "robert", "");
}
#Test
public void runQuery() throws Exception {
try (Connection connection = getConnection();
PreparedStatement ps = connection.prepareStatement("SELECT relname FROM pg_catalog.pg_class");
ResultSet data = ps.executeQuery()) {
while (data.next()) {
data.getString("relname");
}
}
}
}
When I run the above test, it fails if I have a typo in the SELECT statement. (Good.) If I have a typo in the column name in data.getString("typo here"), that won't get caught if the table queried does not have data because then the loop is never entered. To keep the test (setup) simple, I don't want to insert data into my tables first.
I guess I could make the column names into constants and DRY up my code and get rid of the problem.
However, I am wondering if there is an easier way... I am lazy and don't want to edit all my queries. Is there a better way to unit-test my SQL?
I am using Postgres 9.5 and JDBC 4.
I guess you already have the answer you seek but just for the sake of answering, you can try using result-set-metadata by using a select * from table and then checking the column names against your query (you'd have to parse the query string I guess...).
I believe it will work for empty tables as well but do note that I have not tested the empty table scenario.