Java - DriverManager.getConnection Access - java

i have the following code to test a link to a access database on a new server, everything works with the existing server and i am able to access the folder. !if.exists returns true and i can open the data base using Runtime.getRuntime().exec("run......... + f); so i know it can see the database. im unable to get a reason for the fail but its 100% failing at Connection conn = de.....
can anyone help me.
running gives following output - Java result: -1073741811
package testing;
import connections.LocalProperties;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NewClass {
public static void main(String[] args) {
try {
File f = new File("\\\\***\\***\\****\\***.accdb");
if (!f.exists()) {
System.out.println("file does not exist" + f.getAbsolutePath());
return;
} else {
System.out.println("file does exist" + f.getAbsolutePath());
}
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + f.getAbsolutePath();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String m_URLString = url;
String m_UserName = System.getProperty("user.name");
String m_Password = "*******";
Connection conn = DriverManager.getConnection(m_URLString, m_UserName, m_Password);
conn.close();
} catch (SQLException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
When running i get the following popups:
Java.exe
If you were in the middle of something, the information might be lost, for more information click here
Error signature
App name:java.exe appver 7.0.30.5 modname:msvcr80.dll

I think you are missing this line-
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Related

No suitable driver found error even if the my-sql connector uploaded into the library

I am new to java and in a learning process. I'm working on connecting my JDE with MySql and I have followed every step necessary. but when I run the code, I got " No suitable driver found for jdbc.mysql://localhost:3306/dbname" error. I reviewed questions already in stackoverflow and other sources; but the provided solution didn’t work for me.
Any suggestions why i got this error even if I uploaded the mysql-connector-j-8.0.31/mysql-connector-j-8.0.31.jar.a screenshot of my code and the error message
package JDBC;
import java.sql.SQLException;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.Connection;
public class JDBC {
public static void main(String[] args) throws SQLException{
String url = "jdbc.mysql://localhost:3306/University";
String username = "root";
String password = "root";
String query = "select * from EngineeringStudents";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
}catch(ClassNotFoundException e) {
//To do auto-generated catch block
e.printStackTrace();
}
try {
Connection con = DriverManager.getConnection(url, username, password);
Statement statement = con.createStatement();
ResultSet result = statement.executeQuery(query);
while(result.next()) {
String UniversityData = "";
for(int i = 1; i <= 6; i++) {
UniversityData += result.getString(i) + ":";
}
System.out.println(UniversityData);
}
}catch(SQLException e) {
e.printStackTrace();
}
}
}
Bro use String url = "jdbc:mysql://localhost:3306/University". Use have missed a colon ':' after jdbc instead you're using '.'

Creating SQLite database in intellij

I have to create a SQLite database that I will ultimately have to insert lines of data from a parsed .csv file. The issue that I'm having is creating the SQLite database in the intellij idea. Using the code below I continue to get the "No suitable driver" error. I believe that I've added the classpath correctly by using Project Structure-> Modules-> Add then selecting my downloaded SQLite .jar file, which in this case is sqlite-jdbc-3.30.1 (1).jar
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
public class mint {
public static void createNewDatabase(String fileName) {
String url = "C:\\SQLite\\sqlite-jdbc-3.30.1 (1).jar" + fileName;
try {
Connection conn = DriverManager.getConnection(url);
if (conn != null) {
DatabaseMetaData meta = conn.getMetaData();
System.out.println("The driver name is " + meta.getDriverName());
System.out.println("A new database has been created.");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
System.out.println("An error occurred while connecting MySQL database");
}
}
public static void main(String[] args) {
createNewDatabase("input-filename.db");
}
}
Screenshot of output
You need to read this tutorial - URL should be like this
String url = "jdbc:sqlite:C:/sqlite/" + fileName;

Execute jar file using PLSQL

I have a a standalone java program and it read the data from REST end point and insert data into table in Server.
package com.test.main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.test.connectdb.ConDataBase;
import com.test.entity.User;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://jsonplaceholder.typicode.com/todos/");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
System.out.println("DONE2");
int responsecode = conn.getResponseCode();
String inline = "";
if(responsecode == 200){
Scanner sc = new Scanner(url.openStream());
while(sc.hasNext())
{
inline+=sc.nextLine();
}
System.out.println("JSON data in string format");
System.out.println(inline);
sc.close();
}else{
throw new RuntimeException("HttpResponseCode:" +responsecode);
}
//-----------------------------------------------------------------------
Connection con = new ConDataBase().buildConnection();
User[] userList = new Gson().fromJson(inline, User[].class);
System.out.println(userList.length);
for (User user : userList) {
//System.out.println(user.getCompleted());
String insert_date = "insert into XX_USER "
+ "(USER_ID)"
+ "VALUES"
+"('"+user.getCompleted()+"')";
try {
PreparedStatement ps_data = con.prepareStatement(insert_date);
ps_data.executeUpdate();
con.commit();
System.out.println("Successfully Inserted");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I need to run this jar file using PLSQL. That means I have transferred this jar file into Linux server path (/home/rest). Oracle database is installed in server. I need to run this jar using PLSQL. Is it possible?
Use the LOADJAVA utility to load the jar file and all other jar dependencies into Oracle's internal classpath (this is different from the operating system's class path).
You will probably also want to change your code to a static method without arguments (rather than main with a string array argument) as it will make invoking the method much simpler.
// package and imports
public class Main {
public static void yourMethodName() {
// your code
}
}
Then you need to use something like:
CREATE PROCEDURE get_todos_from_rest_service AS
LANGUAGE JAVA NAME 'com.test.main.Main.yourMethodName()';
To create a procedure wrapper around the java method which you can then invoke in PL/SQL.
A more detailed example can be found here: Database Java Developer's Guide - Java Stored Procedures Application Example

java how to connect to a MySQL database in OpenShift

package library;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class conexion {
private String server = "jdbc:mysql://" + System.getenv("OPENSHIFT_MYSQL_DB_HOST") + ":" + System.getenv("OPENSHIFT_MYSQL_DB_PORT") + "/" + System.getenv("OPENSHIFT_APP_NAME") + "";
private String user = System.getenv("OPENSHIFT_MYSQL_DB_USERNAME");
private String pass = System.getenv("OPENSHIFT_MYSQL_DB_PASSWORD");
private Connection conn;
public Connection conectar() throws ClassNotFoundException, SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
this.conn = DriverManager.getConnection(server, user, pass);
} catch (Exception ex) {
Logger.getLogger(conexion.class.getName()).log(Level.SEVERE, null, ex + ex.getMessage());
}
return this.conn;
}
}
I have a java application lodged in OpenShift but when I try to connect it to the cartridge mysql nothing happens when you connect. only it stays in the servlet and takes no other action
Depending on what type of java server you are running on OpenShift, try reading through one of these articles, which should help you get your database connection up and running:
Tomcat: https://developers.openshift.com/en/tomcat-ds.html
JBoss AS: https://developers.openshift.com/en/jbossas-ds.html
JBoss EAP: https://developers.openshift.com/en/jbosseap-ds.html
WildFly: https://developers.openshift.com/en/wildfly-ds.html

JDBC connectivity with open office database

I am using openoffice database for my project....Please help me know how to connect to open office database using JDBC.
Below code is for JAVA. Transform to JSP accordingly.
import java.text.ParseException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main
{
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws ParseException
{
try
{
String db_file_name_prefix = "c:\\mydbdir\\mydb";
Connection con = null;
// Load the HSQL Database Engine JDBC driver
// hsqldb.jar should be in the class path or made part of the current jar
Class.forName("org.hsqldb.jdbcDriver");
// connect to the database. This will load the db files and start the
// database if it is not alread running.
// db_file_name_prefix is used to open or create files that hold the state
// of the db.
// It can contain directory names relative to the
// current working directory
con = DriverManager.getConnection("jdbc:hsqldb:file:" + db_file_name_prefix, // filenames
"sa", // username
""); // password
Statement statement = con.createStatement();
//look at " for table name
ResultSet rs = statement.executeQuery("SELECT * FROM \"User\"");
//print the result set
while (rs.next())
{
System.out.print("ID: " + rs.getString("ID"));
System.out.print(" first name: " + rs.getString("firstname"));
System.out.println(" last name: " + rs.getString("lastname"));
}
statement.close();
con.close();
} catch (SQLException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
} catch (ClassNotFoundException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Never tried it but seems like OpenOffice uses HSQLDB database underneath in file mode. Looks like you can connect to this HSQLDB database directly: Java: Creating a JDBC Connection to OpenOffice.Org Databases.
See also:
How to connect to a "normal" (not embedded) HSQL database?

Categories