Selenium with postgreSQL [duplicate] - java

This question already has answers here:
Cannot simply use PostgreSQL table name ("relation does not exist")
(18 answers)
I keep getting the error "relation [TABLE] does not exist"
(1 answer)
Closed 2 years ago.
I'm trying to connect Selenium with Postgres and the following error is shown:
FAILED: selectQuery org.postgresql.util.PSQLException: ERROR: relation
"login" does not exist
My code is below:
package Posgress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.testng.annotations.Test;
#Test public class PosgressTest {
public static void selectQuery() throws SQLException, ClassNotFoundException {
//Load MySQL JDBC Driver
Class.forName("org.postgresql.Driver");
Connection connection =
DriverManager
.getConnection("jdbc:postgresql://localhost:5432/DIC","postgres", "root");
Statement st = connection.createStatement();
System.out.println("Connection");
String selectquery = "Select * from Login";
System.out.println("Connection1");
// Executing the SQL Query and store the results in ResultSet
ResultSet rs = st.executeQuery(selectquery);
// While loop to iterate through all data and print results
while (rs.next()) {
System.out.println(rs.getString("username"));
System.out.println(rs.getString("password"));
}
// Closing DB Connection
connection.close();
}
}
I have a table 'Login inside schema "DICschema'. I wrote select query like this also "Select * from DICschema.Login" then also same error

You should rename the table to "login" and the schema to "dicschema", not "Login" and "DICschema". Because the query will ignore the case of text.
The query will be like:
"Select * from dicschema.login"

If you want to keep your schema and table name as it is (not changing the character cases), the following query should work for you.
String selectquery = "SELECT * FROM \"DICschema\".\"Login\" ";
This is because when the string in compiled, it changes to lowercase and it can be avoided by using backslash.

It seems that postgres users are unable to access the DIC schema.
Try to attach the prefix(schema) name to the query.

Related

resultSet is null, how ever mysql query is correct

I have problem with my java code (Resultset is null). It was working on localhost until I have tried remote Mysql scalegrid hosting . The most interesting is that, if I use Mysql Workbench query works fine and returns all rows. What I am doing wrongly.
I have tried to commit my table manually;
Query (SELECT * FROM ShopDatabase.DATA) works fine;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.sql.*;
public class Main {
public static void main(String[] args) throws ParserConfigurationException, IOException, SQLException, ClassNotFoundException {
String userName = "App";
String password = "AppShopData+2";
String connectionUrl = "jdbc:mysql://SG-ShopDatabase-821-master.servers.mongodirector.com:3306/ShopDatabase";
try(Connection connection = DriverManager.getConnection(connectionUrl, userName, password)){
System.out.println("Connection established");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM ShopDatabase.DATA where product_name = 'Хлеб';");
while(resultSet.next()){
System.out.println(resultSet.getInt("id"));
System.out.println("----------------");
}
}
}
}
Remove ; at the end of the query:
ResultSet resultSet = statement.executeQuery(
"SELECT * FROM ShopDatabase.DATA where product_name = 'Хлеб'");
Given the correct MySQL connection and that there is indeed a column value 'Xлеб' there:
Remove ";" at the end of the query and check
If the above won't work, eliminate possible internationalization issues (whatever they can be): Store "Bread" instead of Xлеб and see whether you have results (Xлеб is bread in Russian). Of course you'll need to adjust the query correspondingly

Can not create database jdbc [duplicate]

This question already has answers here:
CREATE DATABASE query using java jdbc and prepared statement returns syntax error [duplicate]
(2 answers)
Closed 4 years ago.
I'm trying to create a database with java jdbc with a method so i'm passing the name type string of database as argument to database but i'm facing an issue which is 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 ''Algebra'' at line 1
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DbTest {
private Connection connection;
public void createDb(String name) throws SQLException {
connection = DriverManager.getConnection
("jdbc:mysql://localhost/?user=root&password=root");
String createDbSql = "CREATE DATABASE IF NOT EXISTS ?";
PreparedStatement createDbStat = connection.prepareStatement(createDbSql);
createDbStat.setString(1,name);
createDbStat.executeUpdate();
}
DbTest() {
try {
createDb("Algebra");
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new DbTest();
}
}
When you use createDbStat.setString(1, name); it will create a query like this :
CREATE DATABASE IF NOT EXISTS 'databasename'
//----------------------------^____________^
And this is a wrong syntax, the correct should be :
CREATE DATABASE IF NOT EXISTS databasename
to solve your problem you can just use :
String createDbSql = String.format("CREATE DATABASE IF NOT EXISTS `%s`", name);
// ^^^^
PreparedStatement createDbStat = connection.prepareStatement(createDbSql);
//createDbStat.setString(1,name); no need for this
createDbStat.executeUpdate();
For security reason
Just for security reason, and to avoid SQL Injection make sure that your database name match this:
if(name.matches("^[a-zA-Z_][a-zA-Z0-9_]*$")){
//Correct name
}
for more details read this Check for valid SQL column name
You can't bind your parameter (1) to the database name-
you'll have to use string concatenation in this case.
Your question is also similar to
How to use a tablename variable for a java prepared statement insert
and
CREATE DATABASE query using java jdbc and prepared statement returns syntax error

need help setting up SQLite on eclipse with java for the first time

I have been trying to figure out how to get SQLite working on eclipse juno. I have been following the instructions on this site http://wiki.eclipse.org/Connecting_to_SQLite. The problem is not every step is exactly as explained so I am guessing on weather I got it right or not. I feel that I have probably gotten it all correct until step 13, there is no SQL Model-JDBC Connection entry. So I have tried step 13-16 with a generic JDBC and with one that says SQLite. The SQLite one does not have a driver which is no surprise due to step 5. Any way that I have tried so far ends up failing ping with details listed below. Someone must have a better way through this process.
java.sql.SQLException: java.lang.UnsatisfiedLinkError: SQLite.Database.open(Ljava/lang/String;I)V
at SQLite.JDBCDriver.connect(JDBCDriver.java:68)
at org.eclipse.datatools.connectivity.drivers.jdbc.JDBCConnection.createConnection(JDBCConnection.java:328)
at org.eclipse.datatools.connectivity.DriverConnectionBase.internalCreateConnection(DriverConnectionBase.java:105)
at org.eclipse.datatools.connectivity.DriverConnectionBase.open(DriverConnectionBase.java:54)
at org.eclipse.datatools.connectivity.drivers.jdbc.JDBCConnection.open(JDBCConnection.java:96)
at org.eclipse.datatools.connectivity.drivers.jdbc.JDBCConnectionFactory.createConnection(JDBCConnectionFactory.java:53)
at org.eclipse.datatools.connectivity.internal.ConnectionFactoryProvider.createConnection(ConnectionFactoryProvider.java:83)
at org.eclipse.datatools.connectivity.internal.ConnectionProfile.createConnection(ConnectionProfile.java:359)
at org.eclipse.datatools.connectivity.ui.PingJob.createTestConnection(PingJob.java:76)
at org.eclipse.datatools.connectivity.ui.PingJob.run(PingJob.java:59)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:53)
Make sure you get the driver from https://bitbucket.org/xerial/sqlite-jdbc/downloads, then import the driver into your project.
Now you can test the configuration by creating a java class Sample.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Sample
{
public static void main(String[] args) throws ClassNotFoundException
{
// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate("DROP TABLE IF EXISTS person");
statement.executeUpdate("CREATE TABLE person (id INTEGER, name STRING)");
int ids [] = {1,2,3,4,5};
String names [] = {"Peter","Pallar","William","Paul","James Bond"};
for(int i=0;i<ids.length;i++){
statement.executeUpdate("INSERT INTO person values(' "+ids[i]+"', '"+names[i]+"')");
}
//statement.executeUpdate("UPDATE person SET name='Peter' WHERE id='1'");
//statement.executeUpdate("DELETE FROM person WHERE id='1'");
ResultSet resultSet = statement.executeQuery("SELECT * from person");
while(resultSet.next())
{
// iterate & read the result set
System.out.println("name = " + resultSet.getString("name"));
System.out.println("id = " + resultSet.getInt("id"));
}
}
catch(SQLException e){ System.err.println(e.getMessage()); }
finally {
try {
if(connection != null)
connection.close();
}
catch(SQLException e) { // Use SQLException class instead.
System.err.println(e);
}
}
}
}
The code will create a database named sample.db, inserting data into, and then prints the rows.

Get the metadata for prepared statement in java with MySql DB

I want to fetch parameter name and parameter type of given prepared statement. I am using MySQL Database. But when I run my program it is throwing an error:
Exception in thread "main" java.sql.SQLException: Parameter metadata not available for the given statement
at this line
String paramTypeName = paramMetaData.getParameterTypeName(param);
I don't know why this is happening. Please anybody help me if possible.
Here's my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getMySqlConnection();
Statement st = conn.createStatement();
String query = "select * from survey where id > ? and name = ?";
PreparedStatement pstmt = conn.prepareStatement(query);
ParameterMetaData paramMetaData = pstmt.getParameterMetaData();
if (paramMetaData == null) {
System.out.println("db vendor does NOT support ParameterMetaData");
} else {
System.out.println("db vendor supports ParameterMetaData");
// find out the number of dynamic parameters
int paramCount = paramMetaData.getParameterCount();
System.out.println("paramCount=" + paramCount);
System.out.println("-------------------");
for (int param = 1; param <= paramCount; param++) {
System.out.println("param number=" + param);
String paramTypeName = paramMetaData.getParameterTypeName(param);
System.out.println("param SQL type name=" + paramTypeName);
}
}
pstmt.close();
conn.close();
}
public static Connection getMySqlConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mydb";
String username = "root";
String password = "";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
}
According to this
Should the driver generate simplified parameter metadata for PreparedStatements when no
metadata is available either because the server couldn't support preparing the statement, or
server-side prepared statements are disabled?
You have to set generateSimpleParameterMetadata to true
use a connection string similar to this
jdbc:mysql://localhost:3306/mydb?generateSimpleParameterMetadata=true
MySQL JDBC driver currently does not support it. I am solving the similar issue and came up with the following workaround:
include H2 database in your project (it can also run in embedded mode or in-memory)
translate your MySQL create database script to H2 syntax (or write it in ANSI so it is compatible with both)
compile prepared statements on H2 database first and get metadata from them - H2 database supports this function and SQL query syntax is similar in most cases - then save the obtained meta information for later use
there might be differences in data types, etc, but in general this should give you about 80% match with MySQL without too much hassle
I know it has much caveats, but it might work in some use cases.
Also consider upgrading MySQL database to 5.7, there are some enhancements related to prepared statements which may help, but I am not very deeply knowledgable about those:
http://dev.mysql.com/doc/refman/5.7/en/prepared-statements-instances-table.html
http://dev.mysql.com/doc/refman/5.7/en/prepare.html
You have not set the parameter to the prepared statements, without which you cannot get parameter metadata. so first set the parameter
pstmt.setInt(val)
pstmt.setString(val)
After adding the parameters you can get the meta data about the parameter.
Hope this helps.

Access mysql database in eclipse using java

I created a simple mysql database table using following query:
CREATE TABLE customer(
name varchar(20),
C_ID int NOT NULL AUTO_INCREMENT,
address varchar(20),
email varchar(20),
PRIMARY KEY(C_ID)
);
Now I want to insert values to this table. My client like this:
package com.orderdata.ws;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import com.mysql.jdbc.Statement;
public class OrderData {
public static void main(String[] args)throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/orderdata","root","chathura");
Statement stmt = (Statement) con.createStatement();
String insert = "INSERT INTO customer(name,C_ID,address,email) VALUES (a,5,b,c)";
stmt.executeUpdate(insert);
}
}
But this gives an exception "Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '(a,5,b,c)' at line 1............"
How can I insert data using eclipse???
When inserting varchar text to MySQL tables, you need to surround it in single quotes like this:
String insert = "INSERT INTO customer(name,C_ID,address,email) VALUES ('a',5,'b','c');";
Access databases need ";" at the end of sql command.
String insert = "INSERT INTO customer(name,C_ID,address,email) VALUES ('a',5,'b','c');";
Edit: And you need to put text data into query like this
VALUES ('a',5,'b','c')
You may need to "escape" ' (quote) characters. I dont know how to do this in java, maybe like this:
VALUES (\'a\',5,\'b\',\'c\')

Categories

Resources