I was trying to connect to MySQL "twitch" database using java with this code below:
import java.sql.*;
public class App {
public static void main(String[] args) throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
//Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc://localhost:3306/twitch";
String username = "root";
String pass = "nfreal-yt10";
Connection con=DriverManager.getConnection(url,username,pass);
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select distinct creator_id from twitch.information where creator_id > 40;");
while (rs.next()) {
System.out.println(rs.getString(1));
}
con.close();
}
catch(Exception e) {
System.out.println(e);
}
}
}
when I executed the code my console throws (Full error):
Loading class `com.mysql.jdbc.Driver'.
This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver
class is generally unnecessary.
java.sql.SQLException: No suitable driver found for jdbc://localhost:3306/twitch
I have added MySQL connector on my directory folder and all stuff which required to be added, yet the error still occurred, why?
When you communicate with your database (located at /localhost:3306/twitch), you must precise the protocol used (eg. your browser use http or https protocol followed with the adress).
JDBC is a driver that can interface with MySQL, but can't directly access to your database. Hence your URL should be:
String url = "jdbc:mysql://localhost:3306/twitch";
EDIT : Class.forName("com.mysql.cj.jdbc.Driver"); is no more needed in general. Details here.
How can I connect to Databricks Delta table using JDBC?
I have tried connecting simba driver but im getting hard time for driver class name and url configuration.
Any solution is appreciated.
I cannot paste code here as its company code.
Thanks in advance.
Check this link below. This has steps to configure delta using JDBC
http://sedeks.blogspot.com/2019/05/how-to-connect-to-databricks-delta.html
code provided in this link:
import java.sql.DriverManager
import java.sql.Driver
import java.sql.Connection
import javax.sql.DataSource
object ScalaJdbcConnectSelect {
def main(args: Array[String]) {
val driver = "com.simba.spark.jdbc41.Driver" //attach the Spark jar to the Classpath.
val url = "jdbc:spark://field-eng.cloud.databricks.com:443/default;transportMode=http;ssl=true;httpPath=sql/protocolvl/o/0/0911-153027-hopes19";
val username = "token"
val password = "<token-value>" //Token generated from databricks profile page.
var connection:Connection = null
try {
// Create the connection
Class.forName(driver)
connection = DriverManager.getConnection(url, username, password)
if(connection != null){
println("Connection Established");
}
else {
println("Connection Failed");
}
// create the statement
val statement = connection.createStatement()
val resultSet = statement.executeQuery("<<Query>") // Profile your query here.
while ( resultSet.next() ) {
// Iterate through Result set
}
catch {
case e => e.printStackTrace
}
connection.close()
}
}
I am trying to create a connection in Arango databse using Java , IDE- Eclipse but while executing the program I am getting the exception "Unauthorized".
Note: I have logged in to Arango Database with user :root
URL- http://127.0.0.1:8529/_db/_system/_admin/aardvark/index.html#logs
Program in Eclipse
import static com.arangodb.*;
public class FirstProject {
public static void main(String[] args) {
ArangoConfigure configure = new ArangoConfigure();
configure.init();
ArangoDriver arangoDriver = new ArangoDriver(configure);
String dbName = "mydb";
try {
arangoDriver.createDatabase(dbName);
System.out.println("Database created: " + dbName);
} catch (Exception e) {
System.out.println("Failed to create database " + dbName + "; " + e.getMessage());
}
}
}
I have used the tutorial https://www.arangodb.com/tutorials/tutorial-java-old/ to write this program and followed all the steps mentioned. Still getting unauthorized exception:
Failed to create database mydb; Unauthorized
You have to set the user and password (default user "root", password empty):
ArangoConfigure configure = new ArangoConfigure();
configure.init();
configure.setUser("root");
configure.setPassword("");
ArangoDriver arangoDriver = new ArangoDriver(configure);
In addition I highly suggest you to update to the new java driver (version 4.1.12). Which comes with a new API and a better performance). There is also a tutorial for it (see here).
The required code for your problem in this version would be:
ArangoDB arangoDB = ArangoDB.Builder().user("root").password("").build();
I need to read from a database. I'm under Windows. I get this error message:
java.sql.SQLException: No suitable driver found for localhost
This is an extract from my code:
public class JavaApplication10 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Properties connInfo = new Properties();
connInfo.put("characterEncoding","UTF8");
connInfo.put("user", "root");
connInfo.put("password", "goskomstat");
conn = DriverManager.getConnection("localhost", connInfo);
Being in Windows command line I can type:
C:\Program Files\MySQL\MySQL Server 5.6\bin>mysql -u root -p
Then I enter the password 'goskomstat' and can operate my databases.
What can I try next?
You need to define your connection as follows:
conn = DriverManager.getConnection("jdbc:mysql://localhost/", connInfo);
That allows you to specify the JDBC driver by using the specific URI prefix.
I am new to database and recently started writing test cases for H2 database.
I want to know how to test a stored procedure in Eclipse. I have seen the following:
http://www.h2database.com/html/features.html#user_defined_functions
How to CREATE PROCEDURE in H2
The sample code given in the h2database link,
"CREATE ALIAS NEXT_PRIME AS $$
String nextPrime(String value) {
return new BigInteger(value).nextProbablePrime().toString();
}
$$;
"
Where should this be declared?and how to run it?
PS - I have the H2 JAR file and am testing it.
If someone can tell me how to write a simple stored procedure in Java for H2, it would be of great help.
Also is there any equivalent of the following in H2?
"begin dbms_output" ?
Thanks.
There is no stored procedure and sql userdefined function in H2 database instead of that we use java methods and create a alias to refer that.We can call that methods using alias.
Below is a simple example:**
DROP ALIAS IF EXISTS MYFUNCTION;
CREATE ALIAS MYFUNCTION AS $$
String getTableContent(java.sql.Connection con) throws Exception {
String resultValue=null;
java.sql.ResultSet rs = con.createStatement().executeQuery(
" SELECT * FROM TABLE_NAME");
while(rs.next())
{
resultValue=rs.getString(1);
}
return resultValue;
}
$$;
You may have overlooked the examples in src/test/org/h2/samples/Function.java. Here's a related example:
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
Statement st = conn.createStatement();
st.execute("CREATE ALIAS getVersion FOR \"org.h2.engine.Constants.getVersion\"");
ResultSet rs;
rs = st.executeQuery("CALL getVersion()");
if (rs.next()) System.out.println("Version: " + rs.getString(1));
Console: Version: 1.4.191
Addendum: The feature is not limited to functions; aliased methods can execute arbitrary Java code. For example, the query() method defined in Function.java may be aliased and called as shown below:
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
Statement st = conn.createStatement();
st.execute("CREATE ALIAS query FOR \"cli.Function.query\"");
rs = st.executeQuery("CALL query('SELECT NAME FROM INFORMATION_SCHEMA.USERS')");
while (rs.next()) {
System.out.println("User: " + rs.getString(1));
}
Console: User: SA
Note that cli.Function.query is a copy of org.h2.samples.Function.query.
Below is the way we used to implemented in our project. It might be helpful :)
package com.procedures;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CRITICAL_ACTIONS {
public static final int SAVE_ACTION(Connection connection) throws SQLException {
try {
Statement statement = connection.createStatement();
return statement.executeUpdate("INSERT INTO SCHEMA1.CRITICAL_ACTIONS(COLLEAGUE_ID,JOURNEY_ID,TYPE,PRODUCT,DESCRIPTION,META_DATA,STATUS) values('12345',11111111,'ABC','Lloyds','hellow','hello','START')");
} finally {
//connection.close();
}
}
public static final ResultSet FETCH_ACTION(Connection connection) throws SQLException {
try {
Statement statement = connection.createStatement();
return statement.executeQuery("SELECT * FROM SCHEMA1.CRITICAL_ACTIONS");
}finally {
connection.close();
}
}
}
Calling H2 Java Stored-procedure in Java :-
jdbcTemplate.update("CREATE ALIAS SAVE_ACTION FOR \"com.procedures.CRITICAL_ACTIONS.SAVE_ACTION\"");
jdbcTemplate.update("CREATE ALIAS FETCH_ACTION FOR \"com.procedures.CRITICAL_ACTIONS.FETCH_ACTION\"");
jdbcTemplate.getDataSource().getConnection().createStatement().execute("call SAVE_ACTION()");
Stored procedure in H2 database is same as java methods.So write java methods and can invoke using aliases.
The H2 is not supporting stored procedures. In place of stored procedure we can create a function which returns an output like a stored-procedures. Same as we're using in registerInOut parameters.
For example, if your QueryConst looks like this:
public static final String INSERT_EMPLOYEE = "{call INSERT_EMPLOYEE(?,?,?)}";
then,
We can use schema.sql(which executes before #Test)
DROP ALIAS IF EXISTS INSERT_EMPLOYEE;
CREATE ALIAS INSERT_EMPLOYEE FOR "com.test.EmployeeDaoImplTest.updateEmpStoredproc";
package com.test;
#ContextConfiguration(locations = { "classpath:configxmltest.xml" })
#RunWith(SpringJUnit4ClassRunner.class)
#Sql(scripts = { "classpath:schema.sql" }, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
public class EmployeeDaoImplTest {
public static final String INSERT_EMPLOYEE = "{call INSERT_EMPLOYEE(?,?,?)}";
#Autowired
EmployeeDaoImpl employeeDaoTest;
and other dependencies....(if any)
#Test
public void testUpdateEmployee() {
..ur logic if any input data settings
assertEquals("Inserted Successfully", employeeDaoTest.updateEmployee(input, INSERT_EMPLOYEE));
}
public static ResultSet updateEmpStoredproc(String name, String w, Integer i) throws SQLException {
SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("input", Types.VARCHAR, 255, 0);
rs.addColumn("error", Types.VARCHAR, 255, 0);
rs.addColumn("count", Types.INTEGER, 10, 0);
rs.addRow(0, "Inserted Successfully");
rs.addRow(1, 10);
return rs;
}
}