As part of my project I am trying to connect it with database. I searched in google for the code and I got the following code. In that I don't understand 2 things - "import com.mysql.jdbc.Driver;" and "new Driver". What do these 2 mean ?
package javasql;
import com.mysql.jdbc.Driver;
import java.sql.*;
public class Connect {
public Connect() throws SQLException{
makeConnection();
}
private Connection koneksi;
public Connection makeConnection() throws SQLException {
if (koneksi == null) {
new Driver();
// buat koneksi
koneksi = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mysql","root","virus");
}
return koneksi;
}
public static void main(String args[]) {
try {
Connect c = new Connect();
System.out.println("Connection established");
}
catch (SQLException e) {
e.printStackTrace();
System.err.println("Connection Failure");
}
}
}
package javasql;
import java.sql.*;
public class SqlStatement {
private Statement statement;
public SqlStatement() throws SQLException{
makeStatement();
}
public Statement makeStatement() throws SQLException{
Connect c = new Connect();
Connection conn = c.makeConnection();
statement = conn.createStatement();
return statement;
}
public void insert(String name,int npm)throws SQLException{
statement.execute("insert into Student values(\""+name+"\","+npm+");");
}
public static void main(String arg[]){
try {
SqlStatement s = new SqlStatement();
s.insert("Ferdi2",3);
s.insert("Anca2",3);
System.out.println("Success");
}
catch(SQLException e){
System.out.println("Failed");
e.printStackTrace();
}
}
}
I use NetBeans IDE to develop my project. When I used these codes I made it as a new project. Then it worked fine. But whenever I tried to include these codes in another projects errors are showing at "import com.mysql.jdbc.Driver;". Why is it so ? Can I use these 2 codes in another projects ?
The driver serves as an interface between your application and the database.
Are you using MySQL? If so, you can find the MySQl Java drivers here.
All you need is
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver")
This acts like class loader and load your driver class for you. For that you need to add the corresponding jar file.
Using import com.mysql.jdbc.Driver; in JDBC code is not a good practice
and you need to import only java.sql.* and javax.sql.*. The reason is to detach the code from the specific driver implementation.
See here for more information how to make JDBC connections. And DriverManager.getConnection(...) is enough to get connection.
Related
I am very new to Java and am simply trying to connect to my MSSQL database and return a list of customers. When I try the JDBC connection, I get a "no suitable driver found" error. When I add a Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver") statement, I get a ClassNotFound error. This seems like it should be a lot easier than it's turning out to be. Please help me either find a suitable driver or how to get access through the Class.forName usage.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
public class DbConn {
public static String getConnString(){
return "jdbc:sqlserver://localhost\\SQLEXPRESS:1433;database=OhHold;";
}
public static void getConnection() {
try
{
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String user = "<USER>";
String pw = "****************";
Connection connection = DriverManager.getConnection(getConnString(), user, pw);
Statement statement = connection.createStatement();
String sql = "select txtCompanyName as company from tblCustomers where intNotActive <> 1";
ResultSet result = statement.executeQuery(sql);
while (result.next()) {
System.out.println(result.getString(1));
}
}
/*
// Handle any errors that may have occurred.
catch (ClassNotFoundException e) {
e.printStackTrace();
}
*/
catch (SQLException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
getConnection();
}
}
I am new to java. I am trying to connect to mariadb from code written in eclipse IDE. Here is my code:
import java.sql.*;
import java.sql.SQLException;
import java.sql.DriverManager;
public class DB {
public static void main(String[] args) {
Connection connection = null;
String url = "jdbc:mariadb://localhost:3306/test";
String user = "root";
String pwd = "123456";
try {
connection = DriverManager.getConnection(url, user, pwd);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("you are connected to database");
}
}
This code is not working in my project; however, when I copied the code to the new java project then I'm not facing the problem and it is working. What could be the reason for this issue and how I can fix it?
Here is error message:
Error: Main method not found in class DB, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Your DB class doesn't need a main method. Also, your main method only specifies if you can connect to the database. You may not use this Connection object anywhere in your FX application. To use this Connection object in your FX application, you should use a method like the one below.
public class DB {
private static final Logger LOGGER = Logger.getLogger(DB.class.getName());
private static final String URL = "jdbc:mariadb://localhost:3306/test";
private static final String USER = "root";
private static final String PWD = "123456";
public static Connection getDBConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(URL, USER, PWD);
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.getMessage());
}
return connection;
}
}
Use this whenever you want to access the database at any point in your FX application.
Connection connection = DB.getDBConnection();
// Whatever you want to do with your Connection object.
connection...
Trying to program that can read a MySql database. Somehow I cannot call the methode connect(). It says:
Error: cannot find symbol"
connect.connnect();
_______^
What I'm trying to do is to have the connnect and getData method in different classes, so I can also use the connect class seperately for other projects.
Main:
import java.sql.*;
public class Main {
public static void main( String argv[]) {
Connect connect = new Connect();
Connect.connect();
GetData getdata = new GetData();
getdata.getdata();
}
}
Connect:
import java.sql.*;
public class Connect{
public Connection con;
public Statement st;
public ResultSet rs;
public connect(){
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/leichtathletik","root","");
st = con.createStatement();
}catch(Exception e1) {
System.out.println("Error: "+e1);
}
}
}
GetData:
import java.sql.*;
public class GetData {
public void getData() {
try {
String query = "select * läufer";
rs = st.esecuteQuery(query);
while (rs.next()) {
String vorname = rs.getString("vorname");
String nachname = rs.getString("nachname");
System.out.println(vorname+" "+nachname);
} // end of while
} catch(Exception e2) {
System.out.println("Error: "+e2);
}
}
}
The "connect"- method on the Connect class needs to have a type.
https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html , can be helpful.
Further more, the youtuber (https://www.youtube.com/channel/UCiczh_Q-rC7VhMV0x6__dBw) can maybe help you get started with java.
To connect my required Database. I am planning to use ConnectionPoolDataSource class. But How can i set the details regarding the database name(to which i want it to be connected) on using this instance. Please Help on this occassion.
Try to read this documentation and example
EDIT
just modified example from above links
prepared steps:
- download MySQL Server
- download mySQL java driver
- download Apache Commons Pool
- download Commons DBCP
- Open MySQL Client like MySQL Workbench and create DB using next script
delimiter $$
CREATE DATABASE `test_stackoverflow` /*!40100 DEFAULT CHARACTER SET utf8 */$$
delimiter $$
CREATE TABLE `test_table` (
`idtest_table` int(11) NOT NULL,
`test_field` varchar(45) DEFAULT NULL,
PRIMARY KEY (`idtest_table`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$
INSERT INTO `test_stackoverflow`.`test_table` (`idtest_table`, `test_field`) VALUES (1, 'test1');
INSERT INTO `test_stackoverflow`.`test_table` (`idtest_table`, `test_field`) VALUES (2, 'test2');
create java project, add to class path , myscl connector, pool and dbcp (you just download all these jars)
add next classes
import org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS;
import org.apache.commons.dbcp.datasources.SharedPoolDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* #author Sergii.Zagriichuk
*/
public class Pool {
private static DataSource ds;
static {
DriverAdapterCPDS cpds = new DriverAdapterCPDS();
try {
cpds.setDriver("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
cpds.setUrl("jdbc:mysql://localhost:3306/test_stackoverflow");
cpds.setUser("root");
cpds.setPassword("root");
SharedPoolDataSource tds = new SharedPoolDataSource();
tds.setConnectionPoolDataSource(cpds);
tds.setMaxActive(10);
tds.setMaxWait(50);
ds = tds;
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
user name and pass should be changed to your db user/password
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MainClass {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = Pool.getConnection();
// Do work with connection
statement = connection.createStatement();
String selectEmployeesSQL = "select * from test_table";
resultSet = statement.executeQuery(selectEmployeesSQL);
while (resultSet.next()) {
printTestTable(resultSet);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
} // nothing we can do
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
} // nothing we can do
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
} // nothing we can do
}
}
}
private static void printTestTable(ResultSet resultSet) throws SQLException {
System.out.print(resultSet.getInt("idtest_table")+", ");
System.out.print(resultSet.getString("test_field"));
}
}
Just run main method and you will see printed test values to console!!!
You could use an instance of DriverAdapterCPDS. This will need to add two libraries, Apache Commons Pool and Apache Commons DBCP. It is very useful when the driver you use does not include an implementation of connection pooling.
You can find a example in http://massapi.com/class/dr/DriverAdapterCPDS.html
now I got some trouble connecting to my database. I know the tables i am looking for exist because when I access them with the command line they can be queried.
Probably some minor oversight but I would love some help.
This is where I make my connection to my database
package persistence;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class DBRegistry {
private static DBRegistry db = null;
private static Connection connection = null;
private DBRegistry() {};
public static synchronized DBRegistry getUniqueInstance() {
if (db == null) {
db = new DBRegistry();
return db;
}
else return db;
}
public synchronized Connection getDBConnection() {
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:src/database/taskMan.db");
return connection;
}
catch (SQLException e) {e.printStackTrace();}
catch (ClassNotFoundException e) {e.printStackTrace();}
return null;
}
public synchronized void closeConnection() {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Here is how I query it
public void create(UUID oid, Object obj) {
Task t = (Task)obj;
String statement = "INSERT INTO `complexTask` (`oid`,`description`,`status`) VALUES (?, ?, ?)";
try {
PreparedStatement dbStatement = db.prepareStatement(statement);
dbStatement.setString(1, oid.toString());
dbStatement.setString(2, t.getDescription());
dbStatement.setBoolean(3, t.getStatus());
dbStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
and finally a stack trace:
java.sql.SQLException: no such table: complexTask
at org.sqlite.DB.throwex(DB.java:288)
at org.sqlite.NativeDB.prepare(Native Method)
at org.sqlite.DB.prepare(DB.java:114)
at org.sqlite.PrepStmt.<init>(PrepStmt.java:37)
at org.sqlite.Conn.prepareStatement(Conn.java:231)
at org.sqlite.Conn.prepareStatement(Conn.java:224)
at org.sqlite.Conn.prepareStatement(Conn.java:213)
at persistence.framework.ComplexTaskRDBMapper.create(ComplexTaskRDBMapper.java:23)
at persistence.PersistanceFacade.create(PersistanceFacade.java:49)
at persistence.persistanceStates.NewState.commit(NewState.java:10)
at persistence.PersistentObject.commit(PersistentObject.java:23)
at domain.objects.Task.commitToDB(Task.java:89)
at domain.TaskRepository.commitToDB(TaskRepository.java:60)
at domain.TaskController.persistanceCommit(TaskController.java:97)
at presentation.TaskControlsJPanel$3.actionPerformed(TaskControlsJPanel.java:127)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2012)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2335)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:404)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:253)
at java.awt.Component.processMouseEvent(Component.java:6175)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:5940)
at java.awt.Container.processEvent(Container.java:2105)
at java.awt.Component.dispatchEventImpl(Component.java:4536)
at java.awt.Container.dispatchEventImpl(Container.java:2163)
at java.awt.Component.dispatchEvent(Component.java:4362)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4461)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4125)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4055)
at java.awt.Container.dispatchEventImpl(Container.java:2149)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4362)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:604)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:275)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:200)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:185)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:177)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:138)
And some JUnit code for good measure, the first test passes and the second fails with a similar error to the one above
package test.persistence;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import persistence.DBRegistry;
import junit.framework.TestCase;
public class TestDBRegistry extends TestCase {
public void testDBRegistryConnection() {
Connection con = DBRegistry.getUniqueInstance().getDBConnection();
assertNotNull(con);
}
public void testTableQuery() throws SQLException {
Connection con = DBRegistry.getUniqueInstance().getDBConnection();
PreparedStatement dbStatement = con.prepareStatement("SELECT COUNT(*) FROM `singleTask`");
assertEquals("should be 1 for successful query", 1, dbStatement.executeQuery());
}
I notice that in both your unit test and your other code you are using back-ticks around the table name. In the latest version of sqlite, this is fine but in older versions it wasn't handled as well I believe. Can you try removing the ticks around the table name or maybe changing them to regular quotes rather than back-ticks?
If that doesn't solve it I would check to be absolutely sure that you are pointing to the correct db file. If you specify a filename that doesn't exist you won't get an error, it will simply create a new database there. I'm not sure what the "current directory" is under the context of your app or unit test but be sure it is pointing to where you think it is. To test this, you could change the db file name to foo.db, run the unit test, then search your machine for foo.db to see where it got created. That will tell you where your app is working off of.
I'm not sure your JDBC connection string is quite right. The connection string you use ends with taskMan.db, but your comment above implies that the name of the database file is taskManDb.db (note the extra Db).
It might not fix your problem with the SQL INSERT, but I don't care at all for your DBRegistry implementation. I'd write it like this:
package persistence;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBRegistry
{
public static Connection getConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
{
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(Statement statement)
{
try
{
if (statement != null)
{
statement.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet resultSet)
{
try
{
if (resultSet != null)
{
resultSet.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
Maybe your table is in a package. so you might have do something like
select * from Tasks.ComplextTask
('Tasks' being the package)
Now just try to find a file with the same name in c:\windows\system32 and you will find it. It tells to us that your path is not correct. Have a nice day;
Please Commit your Connection after created table and after insertion.