I am running a server that receives queries and sends them to the Database using Statements.
try{
connection = dbConnection.getDbConnection();
if(connection != null) {
System.out.println("DA2");
Statement mySt = connection.createStatement();
if(mySt != null) {
ResultSet myRs = mySt.executeQuery(query);
System.out.println("DA3");
while(myRs.next()){
//getting data and printing it
}
}
}
It prints DA2 so the connection is created succefully.
The query is send by the client in the following way
DataOutputStream out = new DataOutputStream(client.getOutputStream());
String query = "USE db_name; SELECT * FROM `tb_name`;";
out.writeUTF(query);
I changed the database name with db_name and the table name with tb_name(I am sure I wrote them correctly in my code).
The server receives them this way
Socket client = socket.accept();
DataInputStream input = new DataInputStream(client.getInputStream());
String query = input.readUTF();
When the server is running and the client sends the query an exception is thrown with the following message(I handled the exceptions to show me this).
SQLState: 42000
Error Code: 1064
Message: 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 'SELECT * FROM `tb_name`' at line 1
The same query runs correctly on a MySQL database.
How can I solve this? Is the database sending back the error and so throwing an exception or is it just the code?
SOLVED: I forgot to specify the database name in the connection.
You could use (single SQL statement with qualified name):
String query = "SELECT * FROM db_name.`tb_name`";
public static Connection dbConnect() {
Connection c = null;
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection("jdbc:mysql://localhost:3306/DBNAME", "USERNAME", "PASSWORD");
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException " + e);
} catch (SQLException e) {
System.out.println("SQLException " + e);
}
return c;
}
Hope you have created dbConnect in similar fashion.
Here We heve included the database name in get connection method
So explicitly no need to use database name for each time until you are accessing another database.
so your query should be
String query = "SELECT * FROM `tb_name`";
Related
Postgres JDBC driver not returning the exact error line number as shown in PGAdmin. When I run the below program :
import java.sql.*;
public class Test {
public static void main(String[] args) {
String query = "SELECT table_name, table_type\n" +
" FROM information_schema.tabls\n" +
" WHERE table_schema='public'\n" +
" AND table_type in ('BASE TABLE','VIEW') ORDER BY table_type, table_name;";
try (Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "postgres")) {
System.out.println("Connected to PostgreSQL database!");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
while (resultSet.next()) {
System.out.printf("%-30.30s %-30.30s%n", resultSet.getString("table_name"), resultSet.getString("table_type"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I am getting the following error :
org.postgresql.util.PSQLException: ERROR: relation "information_schema.tabls" does not exist
Position: 38
But when I run the same query on pgadmin4, I receive the following error :
ERROR: relation "information_schema.tabls" does not exist
LINE 2: FROM information_schema.tabls
^
SQL state: 42P01
Character: 38
I want the line number in java program as well. How can I get it?
PGAdmin4 is a node.js backend that uses Python driver psycopg2. This driver is nothing more than a wrapper for C driver named libpq, created by the PostgreSQL team.
JDBC driver communicates with database and uses responses received from the server. org.postgresql.core.v3.QueryExecutorImpl#receiveNoticeResponse private method responsible for parsing server errors and it just creates new org.postgresql.util.ServerErrorMessage instance. So, the response given by the server is equal to the response shown by the JDBC driver.
But as for libpq, messages received from the server, and shown on client-side aren't the same. There is reportErrorPosition method in libpq sources exactly for adding line information. Here is reference for reportErrorPosition sources for PostgreSQL 13.3. Here is place where LINE: x is added to the client error.
Summary
You need to calculate the line number by yourself when using the JDBC driver. Or use C library which does it for you.
I'm getting a syntax error in my prepared statement even though my query runs in SQL Management Studio. I am using GlassFish 4.1.1. What am I doing wrong?
I've tried switching the syntax around a bit but I always get an error.
Here is my connection pool code:
try {
InitialContext ic = new InitialContext();
dataSource = (DataSource) ic.lookup("java:comp/env/" + database);
} catch (Exception ex) {
ex.printStackTrace();
}
Here is my query code:
ConnectionPool pool = new ConnectionPool("BoxPointHAMBURGO");
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String query = "SELECT Tabla FROM BoxPointHAMBURGO.dbo.NombresTablas";
ps = connection.prepareStatement(query);
rs = ps.executeQuery();
} catch (Exception ex) {
System.err.println("Error: " + ex.getMessage());
}
The error that I get is:
Syntax error: Encountered "." at line 1 column 39.
As per this answer the double dot .. operator results in default schema for the current database user being used for the query. However you shouldn't expect that SQL Management Studio query syntax will work when using JDBC. These are two completely different driver interfaces with different limitations, JDBC most likely being more restrictive.
You probably should select the BoxPointHAMBURGO database when you establish the JDBC connection. You would have to modify the JDBC URL as per Building the Connection URL the syntax is:
jdbc:sqlserver://localhost;databaseName=BoxPointHAMBURGO
and then remove the database name from the SQL query:
SELECT Tabla FROM dbo.NombresTablas
Do note that tables under dbo schema can only be accessed by the user that is the database owner.
I'm trying to update a table in my postgres DB with JDBC, and for most of my queries it works just fine. But sometime I get this error:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "CONFLICT"
When I do the request manually in postgres it works just fine:
INSERT INTO user_jira (key_user,account_id,name_user,email_adress,display_name,active)
VALUES ('admin','5a283eThisIsJustAnExample','admin','john.john#proceedit.com','john john',true)
ON CONFLICT (key_user)
DO UPDATE
SET account_id=excluded.account_id,
name_user=excluded.name_user,
email_adress=excluded.email_adress,
display_name=excluded.display_name,
active=excluded.active;
Does anyone konws whats going on?
Edit: here is how I connect to the db and send my query:
String url = "jdbc:postgresql://host:port/db";//connect(url);
Properties props = new Properties();
props.setProperty("user","user");
props.setProperty("password","*********");
try {
dyDATAconn = DriverManager.getConnection(url, props);
System.out.println("connected to "+url);
Statement st;
//sql statement
st = dyDATAconn.createStatement();
int userRowInserted = st.executeUpdate(User.sqlUpdate(newUser));
int taskRowInserted = st.executeUpdate(Task.sqlUpdate(allTask));
int timeSpentRowInserted = st.executeUpdate(TimeSpent.sqlUpdate(allTimeSpent));
System.out.println("tsk: "+taskRowInserted+"\nTS:"+timeSpentRowInserted);
} catch (SQLException e) {
System.out.println("connection to dyJIRA#dyDATA failed");
System.out.println(User.sqlUpdate(newUser));
e.printStackTrace();
return -1;
}
I can't show how I create my query, but I only got pb with users and the requests are all the same format as the one above
I'm writing an application with java form and sqlite and I have a function to connect to database and get data like this:
public ResultSet getResultSet(String query) {
Connection conn = null;
ResultSet rs = null;
try {
// create a database conn
conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\nguye_000\\Desktop\\qlct.db");
Statement statement = conn.createStatement();
statement.setQueryTimeout(30);
rs = statement.executeQuery(query);
return rs;
}
catch(SQLException e) {
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally {
try {
if(conn != null)
conn.close();
}
catch(SQLException e) {
// conn close failed.
System.err.println(e);
}
}
return rs;
}
Why when I call it in main function I get an error?
Database db = new Database();
ResultSet rs = db.getResultSet("SELECT * FROM qlct_options");
while(rs.next()) {
// read the result set
System.out.println("id = " + rs.getInt("option_id"));
System.out.println("name = " + rs.getString("option_key"));
System.out.println("value = " + rs.getString("option_value"));
}
id = 0
name = null
value = null
Exception in thread "main" java.sql.SQLException: [SQLITE_MISUSE] Library used incorrectly (out of memory)
at org.sqlite.core.DB.newSQLException(DB.java:890)
at org.sqlite.core.DB.newSQLException(DB.java:901)
at org.sqlite.core.DB.throwex(DB.java:868)
at org.sqlite.jdbc3.JDBC3ResultSet.next(JDBC3ResultSet.java:83)
at qlct.Qlct.main(Qlct.java:18)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
I want to everytime run a any query I can use getResultSet() function and pass query into it. I can't write a code like this http://chuoidichvu.com/downloads/Database.java, each time I need to write a query I do try{} catch{}, final{}. It's hard!
You return a ResultSet from your function after having close the connection (in the finally part of the outer try).
This causes an error, since you can scan the ResultSet only while the Statement and the Connection are still open.
To obtain your objective (“reuse connect function database java mysqlite”) you have to “rearrange” the abstraction that you are trying to define. For instance you could pass to your method a lambda expression (if you are using Java 8) that processes the result inside it.
So a little background on my problem: I am trying to copy over a table on an Microsoft SQL system from an Oracle database. Besides giving password and user access to the table I cannot edit or do anything to the MSSQL database.
I successfully used the Oracle SQL Developer to connect and view the tables I want (using a third party JDBC driver), but I want to set up an automated copy-over into my Oracle database so I am attempting to use the same driver in some stored java code.
I have a java function that all it should do is go and count the number of entries in the table. So far my code looks like:
public static String getCount() {
Statement stmt = null;
Connection conn = null;
int rowCount = 0;
String message = "";
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.err.println("Error loading driver: " + e);
message = message + e + " -ER1 \n";
}
try {
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://site.school.edu:2000/ACCESS", "user", "password");
stmt = conn.createStatement();
String strSelect = "select 1 as field;";
ResultSet rset = stmt.executeQuery(strSelect);
while (rset.next()) {
++rowCount;
}
}
catch(SQLException ex) {
ex.printStackTrace();
message = message + ex.getSQLState() + " -ER2";
}
finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch(SQLException ex) {
ex.printStackTrace();
message = message + ex.getSQLState() + "-ER3";
}
}
return message;
}
Which is being calling from a stored function :
CREATE OR REPLACE function Schema.java_testMessage return varchar2
as language java
name 'ConnectAndQuery.getCount() return java.lang.String';
Which I am calling from a script in TOAD:
set serveroutput on;
declare
words varchar2(400);
begin
words := KSL_ADMIN.java_testMessage;
dbms_output.put_line(words);
end;
However the result is that I'm getting:
java.lang.ClassNotFoundException: net/sourceforge/jtds/jdbc/Driver -ER1
08001 -ER2
PL/SQL procedure successfully completed.
I have the jar file within the class path, I can't think of any reason it shouldn't have the nessecary permissions to see the jar, and as far as I can tell I have everything spelled correctly.
Please help me figure out what I am doing wrong. Or if there is perhaps an easier way to go about connecting an Oracle DB to an MSSQL DB without really installing anything. Any knowledge on this is welcome as I am pretty new to a lot of this.
Oracle has its own internal java virtual machine and it does not use the system classpath. If you need external libraries you must “load” them into the internal JVM. You can do this using Oracle's loadjava tool.
See the Oracle's loadjava documentation (http://docs.oracle.com/cd/B28359_01/java.111/b31225/cheleven.htm#JJDEV10060)