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
Related
Im trying to use SimpleJdbcCall from spring.jdbc calling function that return a cursor and im getting following error:
org.springframework.jdbc.UncategorizedSQLException: CallableStatementCallback; uncategorized SQLException for SQL [{? = call dbo.api_config_select(?)}]; SQL state [34000]; error code [0]; ERROR: cursor "<unnamed portal 1>" does not exist; nested exception is org.postgresql.util.PSQLException: ERROR: cursor "<unnamed portal 1>" does not exist
This is PostGreSQL function code:
CREATE OR REPLACE FUNCTION "dbo"."api_config_select" (in "_id" integer) RETURNS refcursor AS
$$
DECLARE
ref refcursor;
BEGIN
OPEN ref FOR
SELECT
1;
RETURN ref;
END;
$$
LANGUAGE 'plpgsql' COST 100
and this is Java code
simpleJdbcCall = new SimpleJdbcCall(jdbcTemplate).withFunctionName("api_config_select").withSchemaName("dbo")
.declareParameters(
new SqlOutParameter("_cursor", Types.OTHER),
new SqlParameter("_id", Types.INTEGER));
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("_id", id);
try {
Map<String, Object> result = simpleJdbcCall.execute(10);
for (String s : result.keySet()) {
System.out.println("6.0 " + result.get(s));
}
}
catch(UncategorizedSQLException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
As soon as app call simpleJdbcCall.execute() im getting error. I tried to pass refcursor name, but getting same error.
Anyone have code sample code of using PostgreSql, Spring JDBC and cursor?
use this code block in your method :
Connection conn = jdbcTemplate.getDataSource().getConnection();
conn.setAutoCommit(false);
CallableStatement proc = conn.prepareCall("{? = call dbo.api_config_select() }");
proc.registerOutParameter(1, Types.OTHER);
proc.execute();
ResultSet results = (ResultSet) proc.getObject(1);
while (results.next())
{
// do something with the results.
}
results.close();
proc.close();
Make sure that you must have use
connection.setAutoCommit(false);
just after the connection check as below:
if (connection != null) {
connection.setAutoCommit(false);
Reason is if you will not use setAutoCommit(false), cursor will be close and while retrieving the data it will fail.
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 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`";
I need to accomplish the following:
1.- Save on different variables each field of a query result (Oracle DB).
The query result could be 1 o more rows (5 average).
2.- Invoke a WebService for each row.
4.- Wait for the WebService answer and then repeat the process.
I think that saving the result of 1 row and then invoke the WebService it easy but the problem is when the query result throws more than 1 row.
How can I do this? Is Arraylist the answer?
EDIT: I am using the following code. How can I print the arraylist to see if the connection is working?
If I run this i get:
com.packagename.SomeBean#1d251891
com.packagename.SomeBean#48140564
com.packagename.SomeBean#58ceff1
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
List<SomeBean> v = new ArrayList<SomeBean>();
String query = "select * from table where ROWNUM BETWEEN 1 and 3";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:user/pass#localhost:port:SID");
stmt = con.createStatement();
rs = stmt.executeQuery(query);
while( rs.next() ){
SomeBean n = new SomeBean();
n.setColumn1(rs.getInt("column1"));
n.setColumn2(rs.getString("column2"));
n.setColumn3(rs.getString("column3"));
n.setColumn4(rs.getInt("column4"));
n.setColumn5(rs.getString("column5"));
n.setColumn6(rs.getString("column6"));
n.setColumn7(rs.getString("column7"));
...
v.add(n);
}
for(SomeBean s : v){
System.out.println(s);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
Answering to your question is quite difficoult.
But I can give you some hints.
Your startpoint is JDBC.
The Java Database Connectivity (JDBC)
The Java Database Connectivity (JDBC) API is the industry standard for database-independent connectivity between the Java programming language and a wide range of databases SQL databases and other tabular data sources, such as spreadsheets or flat files. The JDBC API provides a call-level API for SQL-based database access.
The Java Database Connectivity (JDBC)
Once you are able to establish a connection to the DB, this snippet can help you answering to your question.
// start connection
List<SomeBean> v = new ArrayList<SomeBean>();
Statement st;
try
{
st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
while( rs.next() ){
SomeBean n = new SomeBean();
n.setFirstField(rs.getInt("firstfield"));
n.setSecondField(rs.getString("secondfield"));
...
...
v.add(n);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
// close connection
Once you have your collection of beans, just write a for loop that calls the webservice one time for each bean.
for(SomeBean s : v){
callToYouWS(s);
}
I am new to JDBC, and I wanted to find out if there is a way to check if a particular database already exists in MySQL.
Let's say I wanted to create a database named students. If the students database is already created in MySQL an error message in Eclipse would state that this students database already exists. However, I wanted to create a Boolean method to check if students database already exists. If it exists then the Boolean method would return false, otherwise if it’s true, then I can create the students database.
How do I do these in Java? Are there any methods in JDBC that does this or do I need to code it from scratch?
I followed mguymons suggestion and this is what I came up:
public boolean checkDBExists(String dbName) {
try {
Class.forName(JDBCDriver); // Register JDBC driver
System.out.println("Creating a connection...");
conn = DriverManager.getConnection(DBURL, USER, PASS); // Open a connection
ResultSet resultSet = conn.getMetaData().getCatalogs();
while (resultSet.next()) {
String databaseName = resultSet.getString(1);
if(databaseName.equals(dbName)) {
return true;
}
}
resultSet.close();
}
catch(Exception e) {
e.printStackTrace();
}
return false;
}
You can get that information from a JDBC Connection using getCatalogs. Here is an example of getting the Catalogs, aka Database names
// Connection connection = <your java.sql.Connection>
ResultSet resultSet = connection.getMetaData().getCatalogs();
// Iterate each catalog in the ResultSet
while (resultSet.next()) {
// Get the database name, which is at position 1
String databaseName = resultSet.getString(1);
}
resultSet.close();
show databases like 'students'
If you get a row back, it exists.
In newer versions of MySQL (5 and above) run this query:
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = '[database name]'
AND table_name = '[table name]';
If the result is 1 it exists.
In Java JDBC that would look something like this:
// Create connection and statement
String query = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema'[database name]' AND table_name = '[table name]'";
ResultSet rs = stmt.executeQuery(query);
rs.next();
boolean exists = rs.getInt("COUNT(*)") > 0;
// Close connection, statement, and result set.
return exists;
You're doing it back to front. The correct technique is to try to create it and catch the exception. The way you want to do it is subject to timing-window problems: it wasn't there when you tested, but it was there when you tried to create it. And you still have to catch the exception anyway.
You should break out of the loop once the target database is found. Otherwise, it's only sensible if your target search is the last in the result set.
public boolean checkDBExists(String dbName) {
try {
Class.forName(JDBCDriver); // Register JDBC Driver
System.out.println("Creating a connection...");
conn = DriverManager.getConnection(DBURL, USER, PASS); // Open a connection
ResultSet resultSet = conn.getMetaData().getCatalogs();
while (resultSet.next()) {
String databaseName = resultSet.getString(1);
if(databaseName.equals(dbName)) {
return true;
break;
}
}
resultSet.close();
}
catch(Exception e) {
e.printStackTrace();
}
return false;
}