Java Database Connectivity doesn't work - java

I have problem to connect to my Database from my Java Code. I am using MS Access Database. I have created DSR Name and selected appropriate Database for my DSR Name.
DSR Name : connectionExample
Operating System : Windows 8 Pro (64 Bit).
Please answer me with full tutorial because I am a newbie.
My Java Code for Database Connection Example is :
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DatabaseConnection {
public static void main(String[] args) {
String uName="ABC",uPass="ABC",uEmail="ABC",uDate="ABC",uContactNo="ABC";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver Loaded");
Connection con = DriverManager.getConnection("Jdbc:odbc:connectionExample");
Statement stmnt = con.createStatement();
String sql = "insert into UserDetail values ('"+uName + "','"+uPass+"','"+uEmail+"','"+uDate+"','"+uContactNo+"')";
int cnt = stmnt.executeUpdate(sql);
System.out.println("Database Updated.");
}
catch (Exception ex)
{
System.out.println(ex);
}
}
}
The Output of my code is :
run:
java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver
BUILD SUCCESSFUL (total time: 0 seconds)

You must add connecter jar file to netbeans project library.
Download jdbc connector jar file.
Copy it to project folder
select project in netbeans choose properties from right click menu.
Select library->add jar file/folder
select jdbc file.
Now your code will work.

Related

Error When Trying Run SQL Server Query through Netbeans

My application is building successfully but won't run the query. Here's what I've done so far:
Downloaded JDBC Driver and used to successfully create connection to database, which is showing in services tab
Added CLASSPATH variable and added C:\Program Files\Java\jre1.8.0_221\bin;C:\Program Files\Java\jdk1.8.0_221\bin;.;C:\Program Files\Java\Microsoft JDBC Driver 7.4 for SQL Server\sqljdbc_7.4\enu\mssql-jdbc-7.4.1.jre8.jar as well as my JRE and JDK bin folders and .
Run below code
import java.sql.*;
public class TestCode {
public static void main(String[] args)
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://mysqlserver:1433;databaseName=mydatabase;integratedSecurity=false;";
Connection conn = DriverManager.getConnection(url, "username", "password") ;
Statement stmt = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("SELECT TOP 10 UserID FROM dbo.Users");
while (rs.next())
{
String userID = rs.getString("UserID");
System.out.println(userID);
}
}
catch (Exception e)
{
System.err.println("Error");
System.err.println(e.getMessage());
}
}
}
The error I'm getting is:
Error
com.microsoft.sqlserver.jdbc.SQLServerDriver
Which is the just the name of my driver. I got this from right clicking on the driver, clicking customize and copying the Driver Class from this Window.
Fixed.
Needed to add JDBC driver file to project library

The import oracle.jdbc cannot be resolved

I am currently working on a project where we have to connect to a database and through Java insert values into our database. Our professor gave us code in order to help us see how to carry that out. I am new to Java and have very little experience in it but I have been watching videos and researching online. My problem is the following: I am working in eclipse and have created a class called _DataGenerator_ all the code that is there is from my professor.
import java.sql.*;
import oracle.jdbc.driver.*;
public class TestDataGenerator {
public static void main(String args[]) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String database = "jdbc:oracle:thin:#131.130.122.4:1521:lab";
String user = "a+MatrNr";
String pass = "Oracle-Passwort";
// establish connection to database
Connection con = DriverManager.getConnection(database, user, pass);
Statement stmt = con.createStatement();
// insert a single dataset into the database
try {
String insertSql = "INSERT INTO person VALUES ('012345678902', 'Erich', 'Schiküta', 'Wien', 1010, 'Rathausstrasse 19', '12-FEB-2000', 'Wien')";
stmt.executeUpdate(insertSql);
} catch (Exception e) {
System.err.println("Fehler beim Einfuegen des Datensatzes: " + e.getMessage());
}
// check number of datasets in person table
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM person");
if (rs.next()) {
int count = rs.getInt(1);
System.out.println("Number of datasets: " + count);
}
// clean up connections
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
The only error I get when trying to run the code is from
import oracle.jdbc.driver.*;
When I put my cursor over the error symbol it says
the import oracle.jdbc cannot be resolved
When I try to run the code the only message I get back is
the statement in Red oracle.jdbc.driver.OracleDriver
I don't know what the problem is. I don't know if it helps to know that I have created my database in oracle SQL developer.
In eclipse, right click your project->Build Path->Config Build Path->find the Libraries tab and press the Add External Jars, locate your oracle jdbc driver in your hard driver and select it. Make sure it appears in the jars list, and then press apply and close.
you can find the oracle jdbc driver in the offical website:
https://www.oracle.com/technetwork/database/application-development/jdbc/downloads/index.html.
After that this issue should disappear.
Well,the jdbc lib of official oracle is not in maven repo,you should download it from Oracle Website and maven install your path.And if you use maven build your project,you can do this:
mvn install:install-file -Dfile=E:/app/Administrator/product/11.2.0/dbhome_1/jdbc/lib/ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar
Then add to dependency like :
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0</version>
</dependency>

jdbc connection established but didnt print the result in eclipse console

I am new to this forum....
Iam tring to connect java project created in eclipse with oracle database xe,
I followed the procedures as descrided in the following link
https://www.youtube.com/watch?v=fMp63HsIRbc
but it didnt print the result in the eclipse console but it also didnt throw the exception as well
what should be the reason
this is my code
package dbmsoracle;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Jdb {
public static void main(String[] args) {
System.out.println("jen");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","murali123");
Statement st = con.createStatement();
String sql="select * from muhil";
ResultSet rs =st.executeQuery(sql);
while (rs.next())
{
System.out.println("executing ...");
System.out.println(rs.getInt(1)+" "+rs.getInt(2));
System.out.println("executed");
con.close();
}
}
catch (Exception e)
{
System.out.println("connection failed");
System.out.println(e);
}
}
i have downloaded my jdbc driver
Oracle Database 11g Release 2 (11.2.0.4) JDBC Drivers
ojdbc6.jar
Certified with JDK 8, JDK 7 and JDK 6: ......
and iam using jdk 8
Firstly check that your connection is establishing with oracle database or not. Here is the connection code try this
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class OracleJDBC {
public static void main(String[] argv) {
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe","system","murali123");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}
I have the same problem. The problem is your code doesn't catch(SQLException e). Because just catch(Exception e) will not make the exception of sql shown in the console. After doing this, you will probably find the Exception is "No suitable driver found for jdbc".
Then, either you can download the mysql-connector-java and add it to your lib, or if your project is Maven, you can just add dependency in your pom file.
After you used Sql+ for entering database, commit the table. Enter 'commit'(without quotes) on the terminal or either close your Sql+ terminal. In your case, you must have closed the terminal after you changed your id from 24, 253 to 1, 2. That is why it ran properly. Got nothing to do with id starting from 1
first of all go and check if your table has any data or not. It seems you just created this table 'muhil' before writing the above code. i'm pretty sure You must have entered some data as well in your new table. Just make sure you have Committed your transaction in the MYSQL Workbench. Just commit it and try to run your code in eclipse again.

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

MySQL issue using Netbeans

OK so I made a mysql database on godaddy.com
I made an admin table there with 3 fields, ID,Username and Password.
In my program I connected to the database and it shows me the tables so I know its connected(Netbeans)
I downloaded Java JDBC driver and put it in the library of my project.
However when I run the program I get this error:
package testdata;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestData {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try
{
String Name = "rsg";
String Pass= "dfgd";
String Host = "blahhhhhhhhhhhhhhh";
Connection con = DriverManager.getConnection( Host,Name, Pass);
Statement stmt = con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String query="DELETE FROM ADMIN";
stmt.executeUpdate(query);
String sql = "SELECT * FROM ADMIN";
ResultSet rs = stmt.executeQuery(sql);
rs.moveToInsertRow( );
rs.updateInt("ID", 1 );
rs.updateString("Username", "CHRIS");
rs.updateString("Password", "CHRIS");
stmt.close();
rs.close();
}
catch(Exception e)
{
System.out.println("ERROR");
e.printStackTrace();
}
}
}
error is:
java.sql.SQLException: No suitable driver found for ****THIS IS MY HostName****
at java.sql.DriverManager.getConnection(DriverManager.java:604)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at testdata.TestData.main(TestData.java:28)
add mysql conntector jar file in your classpath.
I thing it's an issue with your host address. Check how should it look in MySql documentation
use
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(DatabaseUrl, DataDaseusername, DatabasePass);
example for DatabaseUrl is given below
jdbc:mysql://192.168.100.100/databasename
mysql-connector-java-5.1.22 download from mysql.com
Insure you have add the jar folder in your project.
I believe its is looking for com.mysql.jdbc.Driver
make sure your connection string is correct for an example "jdbc:mysql://remot-example-mysql999.servage.net:3306/databasename?zeroDateTimeBehavior=convertToNull";
Your JDBC connection string is not correct (you cannot simply use the hostname). You need to use a JDBC URL, which for MySQL takes the form:
"jdbc:mysql://<hostname>:<port>/<database>"
Where <port> is optional if your server is running on the default, and is also optional. Change your getConnection method to this:
connection = DriverManager.getConnection(String.format(
"jdbc:mysql://%s:%s/%s", Host, "3306", "YourDBName"),
Name, Pass);
Replace "YourDBName" with the name of the database you are trying to connect to. You also need to have the MySQL driver JAR in your classpath.

Categories