I'm learning how to connect to mysql from java from a book, but I get one error, the first line..the package declaration. I copied the code(given bellow) exactly as it was in the book and I have downloaded everything correctly, please help! Thanks!
package mysql;
import java.sql.*;
public class test {
Connection connection;
private void displaySQLErrors(SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}
public test() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (SQLException e) {
System.err.println("Unable to find and load driver");
System.exit(1);
}
}
public void connectToDB() {
try {
connection = DriverManager.getConnection(
"jdbc:mysql://localhost/accounts?user=&password=");
}
catch(SQLException e){
displaySQLErrors(e);
}
}
public void executeSQL() {
try{
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(
"SELECT * FROM acc_acc");
while (rs.next()) {
System.out.println(rs.getString(1));
}
rs.close();
statement.close();
connection.close();
}
catch(SQLException e) {
displaySQLErrors(e);
}
}
public static void main(String[] args){
test test1 = new test();
test1.connectToDB();
test1.executeSQL();
}
}
If you have an error on your package declaration, it's probably because you don't have it in the right package!
If you have package mysql; as you state in your code, then you need it to be in the mysql folder in your source tree.
Add Mysql jar then this code will be connect.
You should write
Class.forName("com.mysql.jdbc.Driver");
to load the drivers and
connection = DriverManager.getConnection("jdbc:mysql://localhost/accounts","yourUsername","yourPassword");
Related
i am new in database want to run first database program with Access but getting SQLException message "DB linking failed!"
i wrote following code with Java 8,and i have configured ucanaccess's libraries.
Java build path
<i>
import java.sql.*;
public class Db {
public static void main(String[] args)throws SQLException
{
Connection con =null;
try{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String dataSource = "jdbc:ucanaccess://D:/Database.accdb";
con=DriverManager.getConnection(dataSource,"","");
Statement st = con.createStatement();
st.executeUpdate("INSERT INTO Table1 (ID, Name) VALUES ('4','ann')");
st.execute("SELECT * FROM Table1");
ResultSet rs = st.getResultSet();
while(rs.next())
{
System.out.println(rs.getString("ID")+rs.getString("Name"));
}
st.close();
con.close();
}
catch(SQLException e)
{
System.out.println("DB linking failed!");
} catch (ClassNotFoundException e) {
System.out.println("Driver loading failed!");
}
}
}
i have added "e.printStackTrace()" in the catch block as following
catch(SQLException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("Driver loading failed!");
}
and got following error messages
error messages
I've got a mysql question within java. I've got a mysql database with different tables. I currently got a database called 'litebans' and a table called 'litebans_mutes'.
Within that table there is a row called reason and under that reason (let's say what's within reason) there's a string called 'This is a test' and 'sorry'; how would I get the string 'This is a test' and 'sorry' associated with the same 'uuid' row in java? Here is a picture explaining more:
Here is an image explaining the sql format
Additionally, i've currently initialized all variables and such in java, i currently have this code:
http://hastebin.com/odumaqazok.java (Main class; using it for a minecraft plugin)
The below code is the MySQL class; api used to connect and execute stuff.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.octopusmc.punish.Core;
public class MySQL {
public static Connection openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
System.err.println(e1);
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://" + Core.host + ":" + Core.port + "/" + Core.database, Core.user, Core.pass);
System.out.println("Currently connected to the database.");
return conn;
} catch (SQLException e) {
System.out.println("An error has occured while connecting to the database");
System.err.println(e);
e.printStackTrace();
}
return null;
}
public static void Update(String qry) {
try {
Statement stmt = Core.SQLConn.createStatement();
stmt.executeUpdate(qry);
stmt.close();
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
}
public static Connection getConnection() {
return Core.SQLConn;
}
public static ResultSet Query(String qry) {
ResultSet rs = null;
try {
Statement stmt = Core.SQLConn.createStatement();
rs = stmt.executeQuery(qry);
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
return rs;
}
}
An example using that api above is shown below:
try {
ResultSet rs = MySQL.Query("QUERY GOES HERE");
while (rs.next()) {
//do stuff
}
} catch (Exception err) {
System.err.println(err);
err.printStackTrace();
}
tl;dr: I want to get the two fields called 'reason' with the give 'uuid' string field.
First , make sure that your using the jdbc mysql driver to connect to the database
Defile a class where you could write the required connection and create statement code.
For example
class ConnectorAndSQLStatement {
ResultSet rs = null;
public Statement st = null;
public Connection conn = null;
public connect() {
try {
final String driver = "com.mysql.jdbc.Driver";
final String db_url = "jdbc:mysql://localhost:3306/your_db_name";
Class.forName(driver);//Loading jdbc Driver
conn = DriverManager.getConnection(db_url, "username", "password");
st = conn.createStatement();
rs = st.executeQuery("Select what_you_want from your_table_name");
while (rs.next()) {
String whatever = rs.getInt("whatever ");
System.out.print(whatever);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Just call this function and the magic :D
Hope it is helpful
Hello guys so I have this simple java to do and I am trying to connect to an sqlite database from eclipse but it doesn't work at all.
Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseConnection {
private String pathDB="C:\\sqlite\\test.db";
private Connection connection=null;
private Statement statement=null;
public DatabaseConnection(String path){
pathDB= path;
}
public void connect () {
try {
Class.forName("org.sqlite.JDBC");
connection= DriverManager.getConnection("jdbc:sqlite:" + pathDB);
statement= connection.createStatement();
System.out.println("Connection to " + pathDB + " "+ "successful");
} catch (ClassNotFoundException notFoundException) {
notFoundException.printStackTrace();
System.out.println("Connection Error!");
} catch (SQLException sqlException) {
sqlException.printStackTrace();
System.out.println("Connection Error!");
}
String query="Insert into Identity values(0,'issam','issam#mail.com')";
try {
statement.executeUpdate(query);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void close() {
try {
connection.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
And the main class:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
DatabaseConnection connection= new DatabaseConnection("test.db");
connection.connect();
connection.close();
}
}
So I have this sqlite database but whenever I run the code it always gives me : Connection to "path" was successful, no matter what path I put...
I think I have done everything correctly, I downloaded the sqlite JDBC file and added it:
enter image description here
I tried adding a new row to a database table, but it always gives me this:
Connection to test.db successful
java.sql.SQLException: no such table: Identity
at org.sqlite.core.NativeDB.throwex(NativeDB.java:397)
at org.sqlite.core.NativeDB._exec(Native Method)
at org.sqlite.jdbc3.JDBC3Statement.executeUpdate(JDBC3Statement.java:116)
at com.issam.iamcore.DatabaseConnection.connect(DatabaseConnection.java:41)
at com.issam.iamcore.Main.main(Main.java:10)
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (Connection is closed)
at org.sqlite.core.DB.newSQLException(DB.java:890)
at org.sqlite.core.CoreStatement.internalClose(CoreStatement.java:109)
at org.sqlite.jdbc3.JDBC3Statement.close(JDBC3Statement.java:35)
at com.issam.iamcore.DatabaseConnection.close(DatabaseConnection.java:63)
at com.issam.iamcore.Main.main(Main.java:11)
Any help would be appreeciated, thanks !
You have successfully connected to the database, but did not create table Identity before executing insert query, as it says in the stack trace:
Connection to test.db successful
java.sql.SQLException: no such table: Identity
Call this before inserting a row:
String createQuery = "CREATE TABLE Identity (id INT PRIMARY KEY NOT NULL, name TEXT, email TEXT)";
statement.executeUpdate(createQuery);
Following is my Java code. In linux, it is working fine but in Windows I'm unable to insert data into the database on local disk. In NetBeans get it all right but .jar file not. JDBC driver see be good.
Connecting to database:
public static Connection connectToDb() {
try {
Connection connection = null;
DriverManager.registerDriver(new org.sqlite.JDBC());
//LINUX PATH
if (OSDetector.isLinux()) {
connection = DriverManager.getConnection("jdbc:sqlite:/home/" + userNameLinux + "/PDFMalwareDataAnalyser/DatabaseSQLite/database.db", NAME, PASSWORD);
//WINDOWS PATH
} else {
connection = DriverManager.getConnection("jdbc:sqlite:C:\\PDFMalwareDataAnalyser\\DatabaseSQLite\\database.db", NAME, PASSWORD);
}
connection.setAutoCommit(true);
if (connection != null) {
System.out.println("Otvorená.");
}
return connection;
} catch (SQLException e) {
System.err.println(e.getClass().getName() + e.getMessage());
// System.exit(0);
}
return null;
}
Insertion:
public void insertDataToDatabase(int idReport) throws SQLException {
connection = new SQLiteJDBC().connectToDb();
PreparedStatement insertCommunication = connection.prepareStatement("insert into table_communication values(?,?);");
insertCommunication.setString(2, communicationsFinal.toString());
try {
insertCommunication.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
insertCommunication.close();
connection.close();
System.out.println("1. --- Insert do tabuľky TABLE_COMMUNICATION OK ---");
}
Try this:
connection = DriverManager.getConnection("jdbc:sqlite:C:/PDFMalwareDataAnalyser/DatabaseSQLite/database.db")
I'm trying to teach myself how to connect to a msaccess database in java.
I have set up a class to access the database as follows
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public abstract class AccessDBConnect2 {
public static Connection connect(){
String fileName = "C:/Users/Bridget/Documents/EmployeeSys.accdb";
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+fileName;
con = DriverManager.getConnection(url,"","");
} catch (Exception e) {
// Handle exceptions ...
System.out.println(e.toString());
System.out.println("A problem accessing the database");
e.printStackTrace();
} finally {
try { if(con!=null) {con.close();} } catch (Exception e) {}
}
return con;
}
public static void closeConnection(Connection conn){
try{
conn.close();
}catch (Exception e){
}
}
Then I have my code which is just trying to select everything from the table.
I have created the table in msAccess and the code seems to get through the connect method in the above code without any problems, indicating it is finding the database and accessing it somewhat. The problem happens when I call the prepareStatement using the connection, i.e. code line:
stm = conn.prepareStatement(sql);
The full code is:
import java.sql.*;
public class Program2{
public static void main(String[] args) {
try{
// Load the JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
// Establishing db connection
Connection conn = AccessDBConnect.connect();
// Displaying all records from employee file
System.out.println("Display records of all employees");
display(conn);
// Closing the connection
AccessDBConnect.closeConnection(conn);
}catch (Exception e){
System.out.println("Error");
}
}
// Display details of all employees
public static void display(Connection conn){
PreparedStatement stm = null;
// SQL statement
String sql = "SELECT * FROM Employee";
ResultSet rs;
try {
stm = conn.prepareStatement(sql); // Prepare the SQL statement
rs = stm.executeQuery(); // Execture the SQL statement
// Navigate through the ResultSet and print
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
String address = rs.getString("address");
System.out.println("ID: \t \t" + id);
System.out.println("Name: \t \t" + name);
System.out.println("Gender: \t" + gender);
System.out.println("Address: \t" + address);
System.out.println(" ");
}
// Closing the resultSet
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void test(){
int a = "hello";
}
}
You are receiving the error because when you try to call .prepareStatement the connection is closed. Your AccessDBConnect2 class contains a finally block that closes the connection before it returns. Fix that class so it leaves the connection open.
By the way, the JDBC-ODBC Bridge has been removed from Java 8 and is effectively obsolete. You might be interested in this alternative:
Manipulating an Access database from Java without ODBC
I've removed the obviously incorrect answer :) another possibility:
I would think the issue is in your connection to the database, try changing 'C:/Users/Bridget/Documents/EmployeeSys.accdb' to 'C:\\Users\Bridget\Documents\EmployeeSys.accdb'