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.
Related
I have a problem when running my code in NetBeans in order to see if mySQL is connected. This is the code:
public static void main(String[] args) {
Connection connect = null;
try{
connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/tUsers?autoReconnect=true/useSSL=TRUE","root","password");
if(connect!=null)
{
System.out.println("Connected");
}
}catch (Exception e)
{
System.out.println("RIP");
}
}
}
when I run it prints out "RIP". When I debugged it line by line, it went from the "connect = DriverManager.getConnection..." to "System.out.println("RIP"), and when I look at the "Exception e" it says "e = (java.sql.SQLNonTransientConnectionException) java.sql.SQLNonTransientConnectionException: Cannot load connection class because of underlying exception: com.mysql.cj.exceptions.WrongArgumentException: Malformed database URL, failed to parse the connection string near '=TRUE'."
Now, why is that?????
I think you need to add
Class.forName("com.mysql.jdbc.Driver"); .
Also, make sure everything in Connection conn = DriverManager.getConnection (String url, String user, String password); are set correctly.
From the url format in your code, it's like you are trying to get direct connect to specific table tUsers in your database. And I dont think that would work. Correct me if I'm wrong whether it's literally your database name or not.
Because the basic url format i know, should be like jdbc:mysql://localhost:3306/yourDBname .
If you already set the url correctly as is written in your post, then the code is
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/tUsers?autoReconnect=true/useSSL=TRUE","root","password");
if(connect!=null)
{
System.out.println("Connected");
}
}catch (Exception e)
{
System.out.println("RIP");
}}}
Hope that could do the work.
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"));
}
}
}
}
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
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.
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.