Class.forName error in Java connecting to SQL Database - java

I'm getting some kind of syntax error and I'm not sure how to resolve it or what I'm doing wrong exactly. I was following a tutorial on youtube, and I followed exactly how it was done in the video. I added the jar file to the project, but its still giving me this error. I'm fairly new to java and just trying to learn how to create a link between a java application and a sql database.
The error is on the line for:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Any help or hints is appreciated
package database_console;
import java.sql.*;
public class DBConnect {
String dbURL = "jdbc:microsoft:sqlserver://localhost:1433;databaseName=TestDB1";
String user = "sa";
String pass = "pass";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
try {
Connection myConn = DriverManager.getConnection(dbURL, user, pass);
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("Select * from Login");
while (myRs.next())
{
System.out.println(myRs.getString("Username"));
System.out.println(myRs.getString("Password"));
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
I haven't written anything into the main yet, what I've posted is the complete code I've done. Here are the error messages I'm getting:
Description Resource Path Location Type Syntax error on token ".", # expected after this token DBConnect.java /database_console/src/database_console line 11 Java Problem
Description Resource Path Location Type Syntax error, insert ")" to complete MethodDeclaration DBConnect.java /database_console/src/database_console line 11 Java Problem
Description Resource Path Location Type Syntax error, insert "Identifier (" to complete MethodHeaderName DBConnect.java /database_console/src/database_console line 11 Java Problem
Description Resource Path Location Type Syntax error, insert "SimpleName" to complete QualifiedName DBConnect.java /database_console/src/database_console line 11 Java Problem

First, ensure you are getting the jar from the correct place: https://msdn.microsoft.com/en-us/sqlserver/aa937724.aspx
Then, add it to your classpath. If you are using eclipse, press CTRL+SHIFT+T and type SQLServerDriver. It must find the class name.
Lastly, your code won't compile. Add the entire code you wrote inside the main method:
public class DBConnect {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String dbURL = "jdbc:microsoft:sqlserver://localhost:1433;databaseName=TestDB1";
String user = "sa";
String pass = "pass";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
try (Connection myConn = DriverManager.getConnection(dbURL, user, pass);
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("Select * from Login")) {
while (myRs.next()) {
System.out.println(myRs.getString("Username"));
System.out.println(myRs.getString("Password"));
}
}
}
}

Related

Java Program compile and run in command prompt successfully but not in myeclips?

I'm learning jdbc and working with Oracle database by writing this simple code. The IDE i'm using is MyEclips. But the problem is when I compile and run this program in command prompt it works properly but when I try to compile and run this program in my IDE i.e. MyEclips it through an error message:
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
import java.sql.*;
class OracleCon{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = null;
String URL = "jdbc:oracle:thin:#localhost:1521:xe";
String UN = "HR";
String PASS = "12345";
con = DriverManager.getConnection(URL,UN,PASS);
Statement stmt = con.createStatement();
String sql = "SELECT * FROM EMPLOYEES";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}
I also set the class path in Environment variable.Environment variable snippet
Verify that the name of the requested class is correct and that the appropriate .jar file exists in your classpath. If not, you must explicitly add it to your application’s classpath.
In case the specified .jar file exists in your classpath then, your application’s classpath is getting overriden and you must find the exact classpath used by your application.
In case the exception is caused by a third party class, you must identify the class that throws the exception and then, add the missing .jar files in your classpath.

eclipse does not show any output

i wrote very simple database query on java using JDBC.
here is the code
import java.sql.*;
public class statement {
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String URL="jdbc:mysql://localhost/emp";
static final String USER="root";
static final String PAS="1234";
public static void main(String [] args){
System.out.println("hello");
Connection con=null;
Statement stmt=null;
try{
System.out.println("creating database connection");
con=DriverManager.getConnection(URL,"root","1234");
String sql="update Employee set age 30 where id =103";
stmt=con.createStatement();
Boolean ret=stmt.execute(sql);
System.out.println("return value is: "+ret.toString());
int rows=stmt.executeUpdate(sql);
System.out.println("rows impacted: "+rows);
stmt.close();
con.close();
}catch(SQLException se)
{
System.out.println("hello");
}
}
}
On my last catch - it was just check if program outputs anything. No error and no warning is given. However, on my console window I get
0 items
message. What is the problem?
p.s. I included all jar files into my project
Can you show us what you typed on the command line or how you ran this?
I cut/pasted it into Eclipse and other than a missing }. I got:
hello
creating database connection
hello
The second hello indicates the SQLException was thrown as I don't have a database running on my workstation.
I'm thinking perhaps you don't really have the java command right.

Problems connecting to sqlite database in java

I am following a tutorial on connecting my SQLite database to a Java application.
When I run the program I get the following error in the console of NetBeans:
run:
Error connecting to the databasejava.sql.SQLException: No suitable
driver found for jdbc:C:\Users\lawman\Documents\Java Working
Directory\LoginSql\src\project123.sqlite
BUILD SUCCESSFUL (total time: 0 seconds)
Here is my directory:
I have code to connect to the database in class tobecalledbymain.
I have main in mainclass which creates an instance of tobecalledbymain.
In my library file, I have sqlite-jdbcs.jar imported.
Here is the code for tobecalledinmain:
import java.sql.*;
public class tobecalledinmain {
public tobecalledinmain(){
Connection con = null;
Statement st=null;
ResultSet rs=null;
try
{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:C:\\Users\\lawman\\Documents\\"
+ "Java Working Directory\\LoginSql\\"
+ "src\\project123.sqlite");
st=con.createStatement();
//select all records from the table employee
//table has three firlds: employeeid,name and surname
rs=st.executeQuery("SELECT * FROM Employee;");
while (rs.next())
{
int id = rs.getInt("Employeeid");
String name = rs.getString("Name");
System.out.println("id = " + id);
System.out.println("name= " + name);
System.out.println();
}
rs.close();
st.close();
con.close();
}catch(Exception e)
{
System.out.println("Error connecting to the database" + e);
}
}
}
Here is the mainclass code:
public class mainClass {
public static void main(String[] args){
new tobecalledinmain();
}
}
;;
I am not sure why we need to semi-colons!
Anyway, when the tutorial concludes he gets a result from the console. I get the said error message.
What are the drivers in the error message referring to and how do I get them?
Your jdbc connection string does not specify sqlite. Try this, and use forward slashes.
Connection con = DriverManager.getConnection("jdbc:sqlite:C:/PATH/TO/database.db");
This was the WRONG answer, pls disregard.
You need to add the .jar for the SQLite database driver to your classpath when you run your code. See https://bitbucket.org/xerial/sqlite-jdbc
You can see how to do that in Netbeans here: How to add a JAR in NetBeans

Showing error-no suitable driver found for jdbc:oracle:thin:#localhost:1521:orcl

I am using jdk1.8 and I am trying to execute a jdbc program manually on oracle 8i. My code is compiling without any error but at the run time its showing error-no suitable driver found for jdbc:oracle:thin:#localhost:1521:orcl. I have already set the class path for jar file. I am using ojdbc7.jar file.
My code is:
import java.sql.*;
class Database
{
public static void main(String arg[])
{
try
{
String url="jdbc:orcl:thin:#localhost:1521:orcl";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(url,"scott","tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from aj1");
while(rs.next())
{
System.out.println("\n"+rs.getInt(1)+" "+rs.getString(2));
}
}
catch(Exception e){e.printStackTrace();}
}
}
Kindly give the solution for this:
You url String must be
String url="jdbc:oracle:thin:#localhost:1521:orcl";
instead of
String url="jdbc:orcl:thin:#localhost:1521:orcl";
and try.

Java "Connection" Class does not connect to the DB

I'm trying to connect my DB with a Java Application i'm creating. What I got so far:
public class DBConnect {
public void DBConnect() {
try {
DBConnect DBConnect = null;
String url = "jdbc:mysql://localhost:3306/ähs_system";
String uName = "**";
String uPass = "**";
// Connection conn = DriverManager.getConnection(url, uName, uPass);
System.out.println("DB Connected");
}
catch (Exception Err) {
System.out.println("Error while connecting: " + Err.getMessage());
System.exit(0);
}
}
}
It's a runnable code although i'm still able to run the code without any error messages if I change my uName and/or Upass. So based on that information i'm gonna say that it's not actually connecting to the database at all...
Anyone with a few tips or tricks I can use?
I've loaded the DB in services and I am able to reach it and add data and run other SQL commands within netbeans but that's basically it. I've also loaded the mysql-connector-java-5.1.35 driver.
Run Code:
public static void main(String args[]) {
try {
DBConnect DBConnect = new DBConnect ();
DBConnect.DBConnect();
}
catch (Exception e){
System.out.println("Cannot connect to DB. Error: " + e.getMessage());
}
Let me know if you need any furthur information!
Updating property file: C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\build\built-jar.properties
Compiling 1 source file to C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\build\classes
C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\src\kiltenros\DBConnect.java:23: error: incompatible types: java.sql.Connection cannot be converted to kiltenros.Connection
Connection conn = DriverManager.getConnection(url, uName, uPass);
1 error
C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\nbproject\build-impl.xml:923: The following error occurred while executing this line:
C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\nbproject\build-impl.xml:263: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 0 seconds)
the error log is clear
java.sql.Connection cannot be converted to kiltenros.Connection
it seems that you imported the wrong class in the beginning of your class
DriverManager.getConnection(url, uName, uPass) return you instance of java.sql.Connection.
btw, change your local variable DBConnect to dbConnect so it won't has the same name as your class DBConnect and it will follow the java convention (lowercase on 1st letter of a variable)
I've very little experience with MySQL, but I avoid using "ä" in a database name. Perhaps, the underscore isn't allowed.
As per your stacktrace it seems you have not imported the correct Connection class. Delete the Connection file in your project and import java.sql.Connection.
The problem seemed to be a corrupted rs2xml.jar file. Once I reloaded it and it worked.

Categories