Presto JDBC Call statements - java

Is it possible to execute CALL system.sync_partition_metadata('dummy','dummy','FULL') using JDBC as Presto JDBC driver does not support CallableStatements?

Presto JDBC driver does not support io.prestosql.jdbc.PrestoConnection#prepareCall methods (please file an issue), but you can use Statement for this:
try (Connection connection = DriverManager.getConnection("jdbc:presto://localhost:8080/hive/default", "presto", "")) {
try (Statement statement = connection.createStatement()) {
boolean hasResultSet = statement.execute("CALL system.sync_partition_metadata('default', 'table_name', 'FULL')");
verify(!hasResultSet, "unexpected resultSet");
}
}
(BTW you can get always get more help with Presto on Trino (formerly Presto SQL) community slack)

Related

JDBC connection not happening [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 7 years ago.
Below is the code I used for jdbc connection
String dbUrl="jdbc:mysql://localhost:3306/mysql";
String user= "kumar";
String pwd="ratiol";
try (Connection connection = DriverManager.getConnection(dbUrl, user, pwd)) {
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
but I got error as below-
Exception in thread "main" java.lang.IllegalStateException: Cannot connect the database!
at jdbcConnection.Jdbcdemo.main(Jdbcdemo.java:22)
Caused by: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/mysql
at java.sql.DriverManager.getConnection(DriverManager.java:596)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at jdbcConnection.Jdbcdemo.main(Jdbcdemo.java:19)
Can you please tell me how can I get jdbc url?
I am using eclipse(mars) in ubuntu 14.04
if you are using netbeans, right click project -->properties -->libraries-->add library and select MySQL JDBC Driver
just add the com.mysql.jdbc.Driver to the lib folder in you program files.
This is what you wrote
try (Connection connection = DriverManager.getConnection(dbUrl, user, pwd)) {
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
it would be like this:
Connection con = null;
try {
//registering the jdbc driver here, your string to use
//here depends on what driver you are using.
Class.forName("something.jdbc.driver.YourFubarDriver");
Connection connection = DriverManager.getConnection(dbUrl, user, pwd)
} catch (SQLException e) {
throw new RuntimeException(e);
}
Please check Class.forName not more needed when using JDBC v.4
Let's take a quick look at how we can use this new feature to load a
JDBC driver manager. The following listing shows the sample code that
we typically use to load the JDBC driver. Let's assume that we need to
connect to an Apache Derby database, since we will be using this in
the sample application explained later in the article:
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection conn =
DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
But in JDBC 4.0, we don't need the Class.forName() line. We can
simply call getConnection() to get the database connection.
Note that this is for getting a database connection in stand-alone
mode. If you are using some type of database connection pool to manage
connections, then the code would be different.
There are plenty of reason for the exception No suitable driver found for jdbc:mysql like
Your JDBC URL can be wrong.
ClassPath/BuildPath/Lib folder missing the connector jar.
Driver Information is Wrong.
Just load the driver first:
Class.forName("com.mysql.jdbc.driver");

Java MySql Connection Through DSN

I am trying to connect to one of my MySql Databases through a System DSN I set up. The DSN is set up correctly with my SSL certs, username, password, port, and the databases populate the DSN database drop down and the "Test" connection passes. I can't seem to get a connection in Java. I have spent 2 days looking through some examples on Stack but they all refer to an Access database and using JDBC-ODBC bridge which is no longer available in Java 8. I tried using UCanAccess with Jackcess but I have gotten no where. The code below is what I have been tinkering with the last few hours. I normally connect to MySql databases with PHP and receive result in JSON or directly with JDBC driver but for this project neither are really an option. Any ideas. I appreciate the help.
//String username = "<username>";
//String password = "<password>";
//String database = "<database_name>";
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
//Connect to cllients MySql Database
Connection conn = DriverManager.getConnection("jdbc:ucanaccess:" + database);
//Call VerifyLabel(<MAC>,<MODEL>); Call provided client
CallableStatement cStmt = conn.prepareCall("{CALL verify(?, ?)}");
//MAC
cStmt.setString(1, "mac address");
//model
cStmt.setString(2, "model");
cStmt.execute();
//Getting results from "Status" column
ResultSet rs1 = cStmt.getResultSet();
//Iterate results and print.
while (rs1.next()) {
System.out.println(rs1.getString("Status"));
}
//Close connection conn
rs1.close();
} catch (SQLException ex) {
Logger.getLogger(CambiumStoredTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(CambiumStoredTest.class.getName()).log(Level.SEVERE, null, ex);
}
Using MySql Driver:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:"+ database);
also tried:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+ database);
Error for MySql Driver:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
1) DSN is most commonly assocatiated with ODBC (and often with MS-Access). Hence all the links. ODBC is NOT required for a DSN.
2) Do NOT use Ucanaccess. Use J/Connector for mySQL.
3) Make sure you can communicate with mySQL from the command line. Then focus on getting a small "hello world" JDBC app to connect. Your second and third examples look OK. Be sure to check the mySQL logs for any warnings/errors.
Well, after an entire day of trying to get this to work and sleeping on it for a couple hours I finally got it to work. UCanAccess and mysql-connector did not work. The easiest thing since no other method of connecting to this clients database was acceptable was to push this application in Java 7 rather than 8. This allowed me to Coo=nnect to my DSN with no problems. I understand that this method is not the best solution but it is what is working flawlessly and efficiently. Also, instead of using some rigged up 3rd party libs and jars, I am able to use Connector/J. Thanks everyone for trying to help me. Just incase anyone else runs into this issue, this is how I made it work.
Develope app in Java 7 - not 8.
Set Up System DSN
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//You do not need to provide username or password if it is setup in DSN
Connection conn = DriverManager.getConnection("jdbc:odbc:"+ database);

Cant connect to mariadb from java - only with mysqldeveloper [duplicate]

I am trying to connect to a database in Mariadb through a simple java application but the connection is told to be unsuccessful and an Exception is thrown. I have done the similar connection using mysql and it was working correctly. The problem is maybe with the driver here.
try{
Class.forName("org.mariadb.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mariadb://localhost:3306/project", "root", "");
Statement statement = connection.createStatement();
String uname="xyz",pass="abc";
statement.executeUpdate("insert into user values('"+uname+"','"+pass+"')");}//end of try block
I looked up the internet for the help and came by that driver class provided by the MariaDB Client Library for Java Applications is not com.mysql.jdbc.Driver but org.mariadb.jdbc.Driver! I changed it accordingly but it seems the problem is with the very first line inside the try block. The driver is not loading at all.
Also, I have added the mysql jar file to the libraries of my java application as in the screen-shot below. Please help me through this.
It appears that you are trying to use jdbc:mariadb://... to establish a connection to a MariaDB server instance using the MySQL JDBC Driver. That probably won't work because the MySQL JDBC Driver would use jdbc:mysql://..., regardless of whether it is connecting to a MySQL server or a MariaDB server. That is, the connection string must match the driver that is being used (rather than the database server being accessed).
The MySQL and MariaDB drivers are supposed to be somewhat interchangeable, but it only seems prudent to use the MariaDB connector when accessing a MariaDB server. For what it's worth, the combination of mariadb-java-client-1.1.7.jar
and
Connection con = DriverManager.getConnection(
"jdbc:mariadb://localhost/project",
"root",
"whatever");
worked for me. I downloaded the MariaDB Client Library for Java from here:
https://downloads.mariadb.org/client-java/1.1.7/
which I arrived at via
https://downloads.mariadb.org/
Additional notes:
There is no need for a Class.forName() statement in your Java code.
The default configuration for MariaDB under Mageia may include the skip-networking directive in /etc/my.cnf. You will need to remove (or comment out) that directive if you want to connect to the database via JDBC because JDBC connections always look like "network" connections to MySQL/MariaDB, even if they are connections from localhost. (You may need to tweak the bind-address value to something like 0.0.0.0 as well.)
An additional note:
Exploring the MariaDB JDBC driver, I found this inside the url parsing file:
Project: https://github.com/MariaDB/mariadb-connector-j.git
File: src/main/java/org/mariadb/jdbc/UrlParser.java
public static UrlParser parse(final String url, Properties prop) throws SQLException {
....
if (url.startsWith("jdbc:mysql:")) {
UrlParser urlParser = new UrlParser();
parseInternal(urlParser, url, prop);
return urlParser;
} else {
if (url.startsWith("jdbc:mariadb:")) {
UrlParser urlParser = new UrlParser();
parseInternal(urlParser, "jdbc:mysql:" + url.substring(13), prop);
return urlParser;
}
}
As you can see, the string "jdbc:mariadb:" is always replaced with "jdbc:mysql:" internally. So when it comes to the MariaDB driver, whether it is :mariadb: or :mysql: it always gets parsed as "jdbc:mysql:".
No difference.
if (url.startsWith("jdbc:mariadb:")) {
....
parseInternal(urlParser, "jdbc:mysql:" + url.substring(13), prop);
....

What is the difference between OCI and THIN driver connection with data source connection between java and oracle XE?

I'm writing the below codes for connection between the java and Oracle 10g XE using 3 way(OCI, THIN and data source), the code is running successfully but don't know difference between the THIN and OCI with data source connection.
1-
public static void main (String args[]) throws SQLException
{
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:oracle:thin:hr/hr#localhost:1521/XE");
Connection con = ods.getConnection();
System.out.println("Connected");
con.close();
}
2-
public static void main(String args[])
{
try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","hr","hr");
System.out.println("Connected Successfully To Oracle");
con.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
3-
public static void main(String args[])
{
try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Native-API (OCI) driver
Connection con = DriverManager.getConnection("jdbc:oracle:oci:#","hr","hr" );
System.out.println("Connected Successfully To Oracle using OCI driver");
con.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Oracle provides four types of drivers for their database, but I'll only enumerate the two you asked about.
The OCI driver is a type 2 JDBC driver and uses native code to connect to the database. Thus, it is only an option on platforms that have native Oracle drivers available and it is not a "pure" Java implementation.
Oracle's JDBC Thin driver is a type 4 JDBC Driver that uses Java sockets to connect directly to Oracle. It implements Oracle's SQL*Net TCP/IP protocol directly. Because it is 100% Java, it is platform independent and can also run from an Applet. (not that you should)
Both the JDBC thin driver and the JDBC OCI driver speak the same network protocol. From the server standpoint there is no difference between the two. The JDBC thin driver is 100% Java and comes in a single standalone jar (some extra jars will be needed for advanced features). The JDBC OCI driver makes JNI calls to the OCI C client library and hence depends on the Oracle full client to be installed (OCI is also what sqlplus uses). Oracle recommends to use the JDBC thin driver which is what most customers use. It's the fastest driver and the most robust one.

Reason for java.sql.SQLException "database in auto-commit mode"

I use sqlite database and java.sql classes in servlet application to batch-insert some data into database.
There are consecutive four inserts of different kinds of data.
Each one looks like this:
PreparedStatement statement = conn
.prepareStatement("insert or ignore into nodes(name,jid,available,reachable,responsive) values(?,?,?,?,?);");
for (NodeInfo n : nodes)
{
statement.setString(1, n.name);
statement.setString(2, n.jid);
statement.setBoolean(3, n.available);
statement.setBoolean(4, n.reachable);
statement.setBoolean(5, n.responsive);
statement.addBatch();
}
conn.setAutoCommit(false);
statement.executeBatch();
conn.commit();
conn.setAutoCommit(true);
statement.close();
But sometimes I get the
java.sql.SQLException: database in auto-commit mode
I found in source code of java.sql.Connection that this exception is thrown when calling commit() while database is in autocommit mode. But I turn autocommit off before and I can't see any place for some parallel execution related issues as for now application is only turned on once.
Do you have any idea how to debug this issue? Maybe there's some other reason for this error (because I just found that exception about database not found or not well configured can be thrown when inserting null into non-null field)?.
May be an issue is with order of statements. Your database statement should be :
PreparedStatement statement1 = null;
PreparedStatement statement2 = null;
Connection connection=null;
try {
//1. Obtain connection and set `false` to autoCommit
connection.setAutoCommit(false);
//2. Prepare and execute statements
statement1=connection.prepareStatement(sql1);
statement2=connection.prepareStatement(sql2);
...
//3. Execute the statements
statement1.executeUpdate();
statement2.executeUpdate();
//4. Commit the changes
connection.commit();
}
} catch (SQLException e ) {
if (connection!=null) {
try {
connection.rollback();
} catch(SQLException excep) {}
}
}finally {
if (statement1 != null) {
statement1.close();
}
if (statement2 != null) {
statement2.close();
}
if(connection != null){
connection.setAutoCommit(true);
connection.close();
}
}
You have to prepare your Statement and create the batch after conn.setAutoCommit(false);.
When running this from a servlet, you have to make sure that the usage of the Connection is synchronized. Multiple requests could set the Connection to a different auto commit mode at nearly the same time. If you use one Connection per request, this will not be an issue. Otherwise, protect the above part with a critical section.
A tip regarding debugging which is applicable for tomcat / eclipse.
1) Enable JDPA debugging for your application server. In tomcat you can do this by adding the following lines to catalina.sh / catalina.bat:
set JPDA_ADDRESS=8000
set JPDA_TRANSPORT=dt_socket
2) Restart the application server
3) Connect with eclipse to your application server. "Debug as" --> "Remote Java Application"
4) Set a break point in above code.
5) Run the servlet.

Categories

Resources