I'm looking into how to connect a web application to an sql 2012 database "MyTestDatabase" with Windows authentication. I have a similar project that is a simple java application that prints out the contents of a table. here's the code for it...
public class sqldriver {
Connection connection = null;
public sqldriver() {}
public boolean doConnection() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager
.getConnection("jdbc:sqlserver://localhost:1433;database=MyTestDB;integratedSecurity=true");
Statement stmt = connection.createStatement();
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException : " + e.getMessage()); return false;
} catch (SQLException e) {
System.out.println(e.getMessage()); return false;
}
return true;
}
All I can find are tutorials for Derby and that's not what I need. The error I keep getting is...
WARNING: Failed to load the sqljdbc_auth.dll cause : no sqljdbc_auth in java.library.path
I've added the sqljdbc_auth.dll to the web-inf/lib, but it doesn't fix the problem. Is there something I've missed?
make sure you add your database in the odbc !!
Go to the start menu and type Odbc then it will appear a dialog >>
select the system dsn tap then select add then select your server whatever Mysql Or ms Access
after that enter your DB info if you select Mysql then save by click ok
then go to your Code and make a string whith your config and send it to the connection object!!
note:
You should delete your constructor and leave the compiler run the default..
To load sqljdbc_auth.dll, you either need to include the DLL in a location on the system PATH, or you need to explicitly specify the java.library.path property in the run configuration of Eclipse.
Related
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 1 year ago.
EDIT (fixed):
I found out how to fix this issue, it apperently had something to do with the fact I used gradle to build my project (which is standard for modding with FabricMC). Because of that, I had to add the MySQL Connector/J to the dependencies in the build.gradle file. After that I built another project and the SQL connection worked!
I didn't need to add it as a library or dependency afterward. I also didn't have to load the driver using Class.forName();
dependencies {
// To change the versions see the gradle.properties file
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
// Fabric API. This is technically optional, but you probably want it anyway.
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
// https://mvnrepository.com/artifact/mysql/mysql-connector-java
implementation 'mysql:mysql-connector-java:8.0.27'
}
Im writing a Minecraft mod using the Fabric API in Intellij Idea and need to communicate with a database that's on another server (which is using DirectAdmin).
I've tried a lot of solutions suggested from different questions, like loading the driver first or installing the Database Manager plugin. Those sadly don't seem to solve the problem.
I have also quadruple-checked if I'm using the correct path to the database, which I seem to be doing.
(Im using Java 16, in case that helps)
I tried make the connection, but keep getting the same error:
java.sql.SQLException: No suitable driver found for jdbc
I have included the mysql-connector-java-8.0.27.jar library and am still getting the error.
After that I also added it as a dependency, but it still doesn't work.
Am I missing something here? I've been reading a lot of these posts but none of the solutions seem to work.
Something I'm suspecting is that I have to add some sort of library to the server the database is on as well, but I don't know how I would do that.
This is the code I use to make the connection. I call the connect() method from my Main class, which is in a try/catch
package nl.egelblad.tutorial.sql;
import java.sql.*;
public class MySQL {
private String host = "185.102.34.56";
private String port = "3306";
private String database = "my_db";
private String username = "db_username";
private String password = "db_password";
private Connection connection;
public boolean isConnected() {
return (connection == null ? false : true);
}
public void connect() throws ClassNotFoundException, SQLException {
if (!isConnected()) {
connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?useSSL=false&autoReconnect=true", username, password);
}
}
public void disconnect() {
if (isConnected()) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public Connection getConnection() {
return connection;
}
}
You have to load driver at the beginning (only one time) :
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// Or "com.mysql.jdbc.Driver" for some old mysql driver
} catch(ClassNotFoundException e) {
getLogger().error("Failed to load driver");
e.printStackTrace();
}
Then, you should check that the given jar is exported with good dependencies. Depending or your minecraft version, maybe it's already include. But it's possible that it's not.
So, you have to change your export settings to include the jar mysql-connector-java-8.0.27.jar in your own.
I could use some help again, out of ideas. :(
I am making JavaFX application that will use SQLite database. OpenJDK 14 with OpenJFX14 is used. In my Eclipse all is working perfectly. I tried for test to make installer with JPackage and that worked too. When I start installed application it starts ok, but for some reason refuse to connect with database.
Here is my project structure:
I have a button where when Stage is loaded I check connection. It is in file PocetnaController:
//testiranje konekcije nakon instalacije
#FXML
public void btnObracunClick(ActionEvent event) {
lblStatus.setText(model.povezanaBaza());
}
And this is code from PocetnaModel that is called:
public String povezanaBaza() {
this.konekcija = Konekcija.poveziBazu();
return (this.konekcija != null) ? "Веза са базом успостављена" : "Повезивање са базом није успело.";
}
When true it returns "Database connection established" in my language and when false "Connection with database failed".
I repeat, in Eclipse all works well. But, when start installed app I am getting "Connection with database failed". So connection returning null for some reason.
My db file is coppied by JPackage in /app folder. I tried to copy manualy Porez.db to root folder where *.exe is. Strange thing, status label doesn't change in that case. And it should, it must return true or false, don't understand that.
This is stage look when started:
Even if I rename database file in /app folder, so it can't be found my connection still returning false and update status accordingly which is ok.
Here is entire Konekcija file who has a role to take care of connection:
public static Connection poveziBazu() {
File baza = new File("Porez.db");
try {
if (baza.exists()) {
Connection con = DriverManager.getConnection("jdbc:sqlite:Porez.db");
return con;
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
My first suspect is something is wrong with my created JAR, but can't be sure. Makes no sense to me to work in Eclipse and no after install.
There are several places you need to check and possibly fix if you ran jpackage with:
jpackage --name SQLiteTest --input C:\Users\Dalibor\Documents\NetBeansProjects\SQLiteTest\dist --main-jar SQLiteTest.jar --runtime-image hello\myjre
Turn on Windows console so that you can see the error messages it is providing - use jpackage --win-console.
After installing your jpackaged release, check the release directory structure.
Make sure it contains the sqllite-jdbc.jar file.
If NOT found fix your --input directories to add the jar.
Check the app\xxx.cfg file for your generated application.
It must contain all your jar dependencies including sqlite-jdbc.jar such as:
app.classpath=$ROOTDIR\app\jars\xxxx.jar;$ROOTDIR\app\jars\sqlite-jdbc.jar
Check that the jlink command you used to build the runtime image hello\myjre includes --add-modules java.sql to combine with the required SQL dependencies.
The app structure created by the installer that jpackage builds is different to the structure you have in Eclipse - files are under app directory, and most importantly the release is only editable with Administrator privileges. Use System property java.launcher.path to adjust the location of the SqlLite database to an editable location
and don't mask exceptions:
public static Connection poveziBazu() {
File baza = new File("Porez.db");
String jhome = System.getProperty("java.launcher.path");
if (jhome != null) {
baza = new File(System.getProperty("user.home"), "Porez.db");
}
System.out.println("Connecting to "+baza.getAbsolutePath()+" exists()="+baza.exists());
try {
return DriverManager.getConnection("jdbc:sqlite:"+baza.getAbsolutePath());
} catch (Exception e) {
System.out.println("Failed connecting to: "+baza);
throw new RuntimeException("Failed to open or create db: "+baza, e);
}
}
I got this error when I changed my java project into an .exe file and then I try it in another PC The Error
here is the code of connecting to SQLite Database
public static Connection dbConnector() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn=DriverManager.getConnection("jdbc:sqlite:C:\\Users\\3542\\Desktop\\DocProject\\DoctorProject.db");
//JOptionPane.showConfirmDialog(null, "connection succesfull");
return conn;
}catch(Exception e)
{
JOptionPane.showConfirmDialog(null, e);
return null;
}
}
I want to find a way when I transfer my application into another PC my database will work fine
I am using Eclipse SQLite and Lanuch4j for .exe
Thanks in Advance
The path doesn't exist. If you want to run it on other pc's I would recommend you to use relative paths instead of an absolute one.
I need to load data from an SQLite file into a java program which I develop in Netbeans.
The file is to be loaded via a swing menu item. I'm using sqlitejdbc as driver.
Here are the code blocks I assume to be important:
// header stuff
package aufgabe_9;
import java.sql.*;
//...
// menu item opening the file
private void mitemOpenFileActionPerformed(java.awt.event.ActionEvent evt)
{
/**
* Handles the dialogue for selecting and loading file.
*/
JFileChooser fileChoose = new JFileChooser();
fileChoose.showOpenDialog(this); //'this' calls the current object
//Load the sql file
try {
String filePath = fileChoose.getSelectedFile().toString();
Connection conn = DriverManager.getConnection("jdbc:sqlite:" +
filePath);
//Close the connection
if (conn != null)
conn.close();
}
catch (SQLException e){System.err.println("Database problem: " + e);}
}
}
//...
When running the program and loading a file via the menu, I get the following error:
java.sql.SQLException: No suitable driver found for jdbc:sqlite:/home/levent
/temp/A9AProbeflaeche.db
After reading the respective stackexchange posts, I understand that this
problem can be caused by (1) a malformed file URL or (2) the driver not being
loaded. Here's some further information:
I added the sqlitejdbc-3.7.2.jar to the library classpath via Tools --> Libraries as well as to the project libraries via Window --> Projects.
I also checked the Classpath by using this function. It contains the path to the jdbc jar-file just as expected.
I can connect to the database via the Services menu without any problems, so I can assume the URL to be correct, as well as sqlite running on my system.
Some OS information: I'm running Netbeans 8.0 on 64 bit ARCH Linux 3.12.9-2.
Can anybody tell me what I'm missing here? Any help appreciated!
Problem solved
Here is the code that works for me:
//...
private void mitemOpenFileActionPerformed(java.awt.event.ActionEvent evt)
{
/**
* Handles the dialogue for selecting and loading file.
*/
JFileChooser fileChoose = new JFileChooser();
fileChoose.showOpenDialog(this);
//Load the sql file
try {
//Get file path
String filePath = fileChoose.getSelectedFile().toString();
//Open connection
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:" + filePath);
//Do stuff...
//Close the connection
conn.close();
}
//"Multicatch":
catch (SQLException | ClassNotFoundException e) {
System.err.println("Database problem: " + e);
}
//...
You probably need to load the driver class so that it registers itself to the DriverManager using the following code:
Class.forName("org.sqlite.JDBC");
Note: this only needs to be called once in your application.
This was a standard procedure before the Java included the ServiceLoader API, now the DriverManager uses that API to register the drivers it finds in the classpath, but the drivers need to declare a file named java.sql.Driver containing the name of the driver class in the directory META-INF\services of their jar.
Can someone please tell me how to connect java file to postgresql database (if possible with code n explanation)
Google is a good start
http://jdbc.postgresql.org/
Here is an example test.java
import java.sql.*;
class test
{
public static void main(String[] args) {
String hostname="", dbname="", username="", password="";
try {
int argno = 0;
hostname = args[argno++];
dbname = args[argno++];
username = args[argno++];
password = args[argno++];
} catch (Exception ex) {
System.err.println("Usage: java -cp driver.jar:. test [hostname] [dbname] [username] [password]");
System.exit(1);
}
try {
Class.forName("org.postgresql.Driver");
Connection connection =
DriverManager.getConnection(
"jdbc:postgresql://"+hostname+"/"+dbname,
username,
password
);
ResultSet rs = connection.createStatement().executeQuery(
"select version() as version"
);
while ( rs.next() ) {
System.out.println(rs.getString("version"));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Download a current driver from JDBC download page, compile this and run like this on Unices:
java -cp [driver_file_name].jar:. test [hostname] [dbname] [username] [password]
On Windows:
java -cp [driver_file_name].jar;. test [hostname] [dbname] [username] [password]
Just wanted to expound on Tometzky's answer for other beginners using the Netbeans IDE in UNIX like me.
I want the driver to be recognized as a library in the IDE. If you go to Tools->Libraries, you will see the current list. Hit "New Library" and type "PostgreSQL JDBC Driver" or whatever name you want to give it. Then in the Classpath tab, hit "Add JAR/Folder" and point to where you've saved your downloaded driver. I'm not sure if there is a "correct" place to store it, I think it rather depends on how you back up your system and if multiple users share it. Somewhere in your home directory is fine.
After that, make a new project of type "Java Application" and paste Tometzky's code into main. In your project tree, right click on Libraries and add the JDBC driver directly to the project. Now you don't have to worry about specifying the driver on the command line.
Build your project and head over to its "dist" folder. Now you can run it with the command
java -jar myprojectname.jar 127.0.0.1 [dbname] [user] [pw]
That of course assumes you are connect to the database server on your own machine. [user] and [pw] refer to your PostgreSQL username and pw.
Also, when you download the documentation it comes as a bunch of html files. Save them somewhere and point your browser to the index.html file (in Firefox it is File-->Open File).