change h2 database creation location using java - java

I tried to create a h2 database using Java. the following coding are working fine.
public static Connection conn;
static String dbName = "check";
static String className = "org.h2.Driver";
static String url = "jdbc:h2:~/" + dbName;
public static Connection getConnection() {
if (conn == null) {
Class.forName(className);
conn = DriverManager.getConnection(url, "sa", "sa");
database created at C location. But i except data should be create at other Drive.

The ~ symbol in the path refers to your home folder. If you want a separate drive you'll have to indicate the absolute path. But that's not a very portable solution though.
Use for instance
static String url = "jdbc:h2:d:/" + dbName;

Related

SQLNonTransientConnectionException Connecting with MySQL in Eclipse

I am trying to write code for bringing a text file's data into a database using Eclipse, MySQL Workbench, and JDBC 8.0.11. It is giving me a ClassNotFoundException. I have looked at multiple other questions, and they have all been fixed by putting the java\com\mysql\jdbc\Driver.java inside the DriverManager.getConnection parameter. I have already done that, and it is still giving me an error. Anyone have any ideas as to why I'm still getting this error?
public static void main(String[] args) throws Exception{
Class.forName //Register JDBC Driver
("*mysql-connector-java-8.0.11.\\src\\legacy\\java\\com\\mysql\\jdbc\\Driver.java*")
.newInstance();
conn = DriverManager.getConnection (url, user, pass);
Statement stmt = conn.createStatement();
String mysql1 = "UPDATE Policy SET " + readAndArray //Changeable file path
("filepath");
}
NEW EDIT
Following #zlakad 's advice, it turns out that you don't need to use Class.forName() if you have Java 6 or higher. Although, now I have a new error: SQLNonTransientConnectionException because of the underlying WrongArgumentException. I'm puzzled as to why it does this because I'm not using the incorrect parameters for DriverManager.getConnection. Any suggestions?
String url = "file path"; //Changeable for MySQL DB
String user = "root";
String pass = "password";
public static void getConnection() throws Exception {
Connection conn = DriverManager.getConnection(url, user, pass);
Statement stmt = conn.createStatement();
Try this:
// None of this belongs in a main method.
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
// where are url, user, pass set? I don't see them.
Connection conn = DriverManager.getConnection(url, user, pass);
Statement stmt = conn.createStatement();
// this is simply wrong.
String mysql1 = "UPDATE Policy SET " + readAndArray("filepath");
}
You're new to Java and JDBC. This is not a good way to do it. I'd recommend that you search the web and SO for some examples of how to do it better.
You have to load driver class for connection not jar file of that class
you shoud try this:
Class.forName("com.mysql.jdbc.Driver");
I was using the wrong format for a database url in the DriverManager.getConnection();
I changed my url to a jdbc:mysql://host:3306/ and it worked.
String url = "jdbc:mysql://*host*:3306/";
Connection conn = DriverManager.getConnection(url, user, pass);

how can i connect from java to mysql server?

The error is that I cant open the connection to mysql database, it must be an error in parameters but I am confused , I have no idea where is the problem.
First you need to create a MySQL schema. Secondly, use JDBC to connect to your recently created database (via localhost - make sure you get the user/password right).
After that you should use DAO-like classes. I'll leave here a Connect class:
public class Connect {
private static final String USERNAME = "root";
private static final String PASSWORD = "12345";
private static final String URL = "localhost";
private static final String SCHEMA = "new_schema";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection connect() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://"+URL+"/"+SCHEMA+"?user="+USERNAME+"&password="+PASSWORD);
}
}
After you have the Connect class, you should connect to the database using Connection c = Connect.connect(). Here's a class that implements it.
public static List<Album> list() throws SQLException {
Connection c = Connect.connect();
ResultSet rs = c.createStatement().executeQuery("SELECT * FROM Albums");
List<Album> list = new ArrayList<>();
while (rs.next()) {
String name = rs.getString("nome"); // first table column (can also use 1)
String artist = rs.getString("artista"); // second table column (can also use 2)
Album a = new Album(name, artist);
list.add(a);
}
return list;
}
It should also give you an insight as to how you should use SQL commands.
If you'd like a more in-depth help you should post the code you used, otherwise it's difficult to give you a more "to-the-point" explanation.
JDBC URLs can be confusing. Suggest you try using a SQL tool that understands the JDBC protocol (such as the database development perspective in Eclipse) to validate the URL and make sure you can connect to the database before you start coding. Cutting and pasting a URL known to work into your code can avoid many problems.

Connecting to database on server

Edited:
I'm trying to connect to my database but I'm stuck.
I get the following error:
I have a mysql database and gain access to it using phpMyAdmin.
Here's my code (UPDATED):
public class DBConnection
{
static String user = "ademphotography_dk_financesjava";
public static String pass = "******";
private static String db = "ademphotography_dk_financesjava";
protected static String url = "jdbc:mysql://ademphotography.dk.mysql";
public static Connection getConnection()
{
Connection conn;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection(url+"/"+db, user, pass);
return conn;
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
I've tried using the IP of the host:
Protected static String url = "jdbc:mysql://XX.XX.X.XX:3306";
but that resulted in this error instead (but now I don't have problem with "unkown host"):
Caused by: java.net.ConnectException: Connection timed out: connect
Wouldn't this Java expression:
url+db
return this string:
jdbc://ademphotography.dk.mysqlademphotography_dk_financesjava
It seems like you need a literal slash character before the database name.
I'd expect that without the slash, that whole string "ademphotography.dk.mysqlademphotography_dk_financesjava" is going to be seen as a hostname.
The connection must be in the form
jdbc:mysql://server/database
In your example the line please update the following two lines:
protected static String url = "jdbc:mysql://ademphotography.dk.mysql";
...
conn = (Connection) DriverManager.getConnection(url+"/"+db, user, pass);
[edit: corrected a wrong line of code]

java database connection confusion

I was some practice code from Big Java 4th on connecting my program to a derby database. I get the following every time though.
Usage: java -classpath driver_class_path;. TestDB database.properties as the output and I can't figure out why it won't connect.
This is my test database:
public class TestDB
{
public static void main(String[] args) throws Exception
{
if (args.length == 0)
{
System.out.println(
"Usage: java -classpath driver_class_path"
+ File.pathSeparator
+ ". TestDB database.properties");
return;
}
else
SimpleDataSource.init(args[0]); `
Connection conn = SimpleDataSource.getConnection();
try
{
Statement stat = conn.createStatement();
stat.execute("CREATE TABLE Test (Name CHAR(20))");
stat.execute("INSERT INTO Test VALUES ('Romeo')");
ResultSet result = stat.executeQuery("SELECT * FROM Test");
result.next();
System.out.println(result.getString("Name"));
stat.execute("DROP TABLE Test");
}
finally
{
conn.close();
}
}
}
This is the connection program supplied:
public class SimpleDataSource
{
private static String url;
private static String username;
private static String password;
/**
Initializes the data source.
#param fileName the name of the property file that
contains the database driver, URL, username, and password
*/
public static void init(String fileName)
throws IOException, ClassNotFoundException
{
Properties props = new Properties();
FileInputStream in = new FileInputStream(fileName);
props.load(in);
String driver = props.getProperty("jdbc.driver");
url = props.getProperty("jdbc:url");
username = props.getProperty("jdbc.username");
if (username == null) username = "";
password = props.getProperty("jdbc.password");
if (password == null) password = "";
if (driver != null)
Class.forName(driver);
}
/**
Gets a connection to the database.
#return the database connection
*/
public static Connection getConnection() throws SQLException
{
return DriverManager.getConnection(url, username, password);
}
}
The usage method is telling you how to run the program correctly. Let me translate that into English, in case for some reason the place where you got this code from doesn't explain it.
Usage:
Here we are going to show how to use the program from a command prompt. If running the program from an IDE it would be similar but you would omit "java" and the classpath and program name would be configured separately.
java
The command to run Java programs
-classpath driver_class_path;.
specifying your classpath as the location of the Derby driver, and then the current directory (where your program lives)
TestDB
The name of your program - which is TestDB, so don't change this
database.properties
The filename of the properties file to use. The properties file contains the database connection parameters. This is a software development good practice! The database password, if any, must match the password you have set up.

Connecting a Java application to an SQL database with Eclipse

I know this has been asked before but I really can't get this to work and as far as I can see I've followed all the steps.
I'm using Eclipse.
So I downloaded the Microsoft SQL Driver sqljdbc v4.0.
I created a new project and class. I edited the build path by adding the .jar file to the libraries.
I typed the following code:
package com.test.sql;
import java.sql.*;
public class Connect
{
public static void main (String[]args)
{
Connection con = null;
String conURL = "jdbc:sqlserver://localhost; databaseName=AnotherTestDB;";
try
{
con = DriverManager.getConnection(conURL);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I got the following error:
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost; databaseName=AnotherTestDB;
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.test.sql.Connect.main(Connect.java:11)
A bit more research and I was told put it in the java /lib/ext and reference it from there.
Nothing changed.
Any help?
Thanks.
Normally you need to register the driver before accessing to it:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Try with something like this:
String DRIVER = “oracle.jdbc.driver.OracleDriver”;
String DBURL = “jdbc:oracle:thin:#jiplc0.si.ehu.es:1512:Erreala”;
String UID = “USERNAME”;
String PWD = “PASSWORD”;
Driver kontrolatzailea = (Driver) (Class.forName(DRIVER).newInstance());
DriverManager.registerDriver(kontrolatzailea);
DefaultContext test = new DefaultContext(DBURL, UID, PWD, false);
DefaultContext.setDefaultContext(test);
Thanks for the responses.
I had both the sqljdbc4.jar and sqljdbc.jar referenced. The version of Java I am using requires that I use sqljdbc4.jar but it was being overwritten by sqljdbc.jar so I removed it.
I also changed my code to this:
public static void main (String[] args)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://nameMyLaptop//SQLEXPRESS";
Connection con = DriverManager.getConnection(connectionUrl);
}
//Insert catches
}
Apparently I didn't have to change the code but its not giving me that error now. I'm getting a new one but that's unrelated to my question.
Thanks for your time and responses.
You have to add the SQL JDBC Driver in your project libraries. download jtds.jar and add to your libraries. And follow the code below.
public static void main (String[] args) throws Exception{
Connection conn=null;
String url="jdbc:jtds:sqlserver://YourServerIp:1433/dbName";
String username="sa";
String password="****";
String driver="net.sourceforge.jtds.jdbc.Driver";
// Step 1: Load the JDBC driver.
Class.forName(driver);
// Step 2: Establish the connection to the database.
conn= DriverManager.getConnection(url, username,
password);
}
Here you have to follow two steps......

Categories