I am using Eclipse IDE Version: Helios Service Release 2 and JDK version 1.6. I have SQL Server 2008 installed on my system. I have downloaded Microsoft JDBC driver and included the path of the jar file in Eclipse IDE-> Project Properties->Java build Path-> Libraries -> Add External jars.
I have written this piece of code for database connection:
package com.ucs.test;
import java.sql.*;
public class ConnectDatabase {
Connection DBconnection = null;
String dbName = "silkopenview";
String userName = "SilkTestAdmin";
String password = "Nbv12345";
Class.forName(drivername);
DBconnection = DriverManager.getConnection(dbName,userName,password);
}
But I get the following errors:
Syntax error on token "DBconnection", VariableDeclaratorId expected after this token
Syntax error on token "drivername", VariableDeclaratorId expected after this token
Syntax error on token(s), misplaced construct(s)
I am new to Java and Eclipse IDE. Please help me in correcting this errors. A quick help is appreciated.
These statements:
Class.forName(drivername);
DBconnection = DriverManager.getConnection(dbName,userName,password);
are currently just part of the class - not in a method, or constructor, or static initializer etc. You probably want to put them in a constructor. The previous ones are okay, as they're variable declarations - although whether you really want them to be instance variables is a different matter.
Also note that driverName isn't declared anywhere in the code you've given.
On a tangential note, if you're sufficiently new to Java that you're running into this sort of thing, you should abandon your current code completely: you're currently trying to run before you can walk. Talking to databases correctly is non-trivial, and trying to learn how to do that while also learning Java syntax is going to be messy. Start with simple console apps that let you learn the language and some of the core types (strings, numbers, collections etc) and then move on to databases.
Class.forName(drivername);
DBconnection = DriverManager.getConnection(dbName,userName,password);
You can not put them where you placed in your class, You have to put them in constructor/method, like :
public class ConnectDatabase {
Connection dbConnection = null;
String dbName = "silkopenview";
String userName = "SilkTestAdmin";
String password = "Nbv12345";
public Connection getConnection() {
Class.forName(drivername);
dbConnection = DriverManager.getConnection(dbName,userName,password);
return dbConnection;
}
}
You need to place your statements in a method rather than in the class block.
Class.forName(drivername);
and
DBconnection = DriverManager.getConnection(dbName,userName,password);
Given that you're using SQL Server, you will need to declare your driverName:
final String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Related
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 1 year ago.
I am currently making a backend reporting system (for a voting system assignment) using Java on VS Code, I am connecting to a MySQL database using the JDBC library in order to do calculations and stats and so on. So what happens is that once I create a project file and include the mysql-connector-java-8.0.25.jar in the referenced libraries, I can connect to the DB and retrieve data from the tables just fine, but after a few executions I no longer get output and it shows me the error "java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver".
Can anyone tell me why this is happening and how to fix this? There are no changes that I know of taking place in the Environment Variables (at least from what I can see in Windows path list) unless something is being overwritten somewhere or that it's a bug of some sort. Any advice would be greatly helpful, I've been unable to figure this out all day
This is what my ReportSystem.java looks like...
import java.sql.*;
public class ReportSystem
{
public static void main(String[] args)
{
//Test driver connection/registration
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ElectionDB","<username>","<password>");
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM ElectionDB.Votes");
int typeColumn = 1;
int districtColumn = 2;
//Output results line by line
while(result.next())
{
System.out.println(result.getString(typeColumn));
System.out.println(result.getString(districtColumn));
}
//Remember to close the connection
conn.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
My file structure as in the directory is as follows:
ReportSystem
>src > ReportSystem.java
> ReportSystem.class
>lib
>.vscode > settings.json
The JRE system library used is: [jdk-16.0.1]
The Referenced Libraries contains: [mysql-connector-java-8.0.25.jar]
Screenshot for context Project Setup in VS Code
I'm able to get result after running code 20 times continuously by clicking the run button. The only difference is the JDBC connection string, which is copied directly by right clicking the MYSQL connection:
So in my project, the connection string is like:
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/?user=username","<username>","<password>");
OR
You could try
String url="jdbc:mysql://localhost:3306/ElectionDB?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"
For your reference, OS Infomation:
MySQL: 8.0 // mysql-connector-java-8.0.25.jar
VSCode: 1.56.2 //
java.home: JDK16 // Debugger for Java: 0.33.1
I am new to PostgreSQL (I normally use other database engines), and I also do not use Java often.
My Problem is that I get the following exception:
java.sql.SQLException: No suitable driver found for DATABASE_NAME
java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at
java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
I followed this tutorial: http://www.postgresqltutorial.com/postgresql-jdbc/connecting-to-postgresql-database/ and added postgresql-42.2.5.jar as a library.
The problem is that adding the driver as a library, as can be seen in the screenshot, has no effect.
So my question is: how do I connect to a PostgreSQL database using Java and the latest IntelliJ?
Any help would be appreciated.
UPDATE 1:
UPDATE 2:
Since the code has been requested: I have replaced the original code by a minimal code that will cause the error:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class IngestData
{
protected static String url;
protected static final String user = "user";
protected static final String password = "password";
public static void main(String[] args)
{
Connection connection = null;
url = args[args.length-1];
try
{
connection = DriverManager.getConnection(url, user, password);
System.out.println("SUCCESS");
} catch (SQLException e)
{
System.out.println("ERROR");
e.printStackTrace();
}
}
}
The console output is:
ERROR
java.sql.SQLException: No suitable driver found for http://127.0.0.1:10282/db01617792
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at IngestData.main(IngestData.java:17)
Process finished with exit code 0
Here is the link to the git repository containing the code:
https://github.com/ka6555/StackOverflow-Postgresql-Problem.git
UPDATE 3:
I found the error:
I need to change
protected static String url;
to
protected static String url = "jdbc:postgresql://";
and
url = args[args.length-1];
to
url += args[args.length-1];
While this solves my original problem, the program is now stuck executing the following line:
connection = DriverManager.getConnection(url, user, password);
There is no error but the program will simply run like with an endless loop never going beyond this code line.
UPDATE 4:
I have fixed all problems now.
It seems like you are missing the postgres jar file in your project dependencies.
Open the Project Structure (Ctrl+Alt+Shift+S on Windows)
Select modules / dependencies tab
You should see something like the following:
If the postgres dependency is missing:
Klick on the + sign on the right side of the screenshot
Choose Library/Project Library and your postgres jar file
Your code should now run. Let me know if it helps.
Note: Please provide your minmal working code on GitHub for a quicker response.
The main problem was that I used a command line parameter as the database url without prefixing it with jdbc:postgresql://. Additionally, I had to reinstall postgresql because of some odd behavior I could not figure out the reason for.
This is the message you get when the URL syntax is incorrect.
This is the requirement.
I have searched solution for a long time on the net but have not found. Please help or try to give some ideas how to achieve this.
Select from table
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/gjp?serverTimezone=UTC";
String user = "root";
String password = "snn0924";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, password);
String sql="select * from gjp_zhangwu";
QueryRunner qr=new QueryRunner();
Object[] params= {};
ZhangWu zw =
qr.query(conn, sql, new BeanHandler<ZhangWu>(ZhangWu.class), params);
It seems that the question is in the last line,but how to use "BeanHandler"?
This happens because the unnamed module from Apache Commons DBUtils cannot access your classes.
That happens because you're using the Java Platform Module System.
To solve this problem you need to export your packages, so that the Apache module can see them.
module your.module {
...
exports your.package;
}
your.package is the package under which your Zhang class resides, with every other class that needs to be used with it.
You classes must also be declared public.
Once you saw that this way it works, you might want to try de-escalating the visibility of your classes, using
opens your.package;
instead.
Using class.ForName to load ucanaccess in a maven project
OK so I am now totally out of my depth. Everything was going so well before I started to use Maven and now its so much more complicated.
Anyway I am trying to connect to a database using ucanaccess.
public Statement ConnectorNoInsert(String HospNum,String SName,String FName,String DOB) throws SQLException{
Preferences userPrefs = Preferences.userNodeForPackage(main.java.Console.TBB_SQLBuilder.class);
String connectDB ="jdbc:ucanaccess://"+userPrefs.get("PathForDB", null);
System.out.println("Connection To Database Made "+userPrefs.get("PathForDB", null));
Connection conn=DriverManager.getConnection(connectDB);
Statement st =conn.createStatement();
return st;
The error that I get is:
ERROR: java.sql.SQLException: No suitable driver found for jdbc:ucanaccess://PhysJava/Physiology.mdb
so I added Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); above the Connection conn line. This gives me the error:
unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown and the project doesnt compile
I suppose the question is: how to call Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); in a maven project. If I need to use a ClassLoader could someone please show me how
The first one ("No suitable driver") is a run-time error, the second one ("unreported exception") a compile-time one. The error message is pretty explicit: "...must be caught or declared to be thrown..." Fix the code in this sense.
Here is my piece of code--
String userName = "username";
String password = "password";
String url = "jdbc:sqlserver://WEBDBSRV/DEVPORTAL;test";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);
I am trying to connect my database in one of my java product but getting following error
The method getConnection(String, String, String) is undefined for the
type DriverManager.
The fact that you did not encounter ClassNotFound exception means that DriverManager is in your classpath. The problem might be one of these things:
wrong DriverManger imported
DriverManager class version used during deployment different than used during development
Some clash between two classes called DriverManger and loaded by different class loaders
Get your jar which contains DriverManager. Unpack it and decompile to see the signatures of methods. The fact that you managed to compile the project means that the version you are using during compilation is probably not the one used during deployment.