I try to connect to db2 from java, here is my code:
public class Db2Connection {
public static void main(String[] args) {
String jdbcClassName="com.ibm.db2.jcc.DB2Driver";
String url="jdbc:db2://localhost:50001/TEST";
String user="user1";
String password="pass";
System.out.println("before try-catch");
Connection connection = null;
try {
System.out.println("try");
//Load class into memory
Class.forName(jdbcClassName);
//Establish connection
System.out.println("before conn");
connection = DriverManager.getConnection(url, user, password);
System.out.println("after conn");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(connection!=null){
System.out.println("Connected successfully.");
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
To be clear, I add db2jcc.jar to my project and run code with valid url. Program cannot jump over line:
connection = DriverManager.getConnection(url, user, password);
I receive no errors or exception, application just not execute. I have no idea how deal with it, can anyone help me?
Try, after removing colon like :
String url="jdbc:db2//localhost:50001/TEST";
Related
I wanted to connect DB to Java application in Intellij.
I set the classpath correctly, so that javac from cmd is working correct.
I have also downloaded all the jar files needed as a libary, but I still get java.sql.SQLException: No suitable driver found for jdbc:derby
What can be the problem?
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch(java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
final String DATABASE_URL = "jdbc:derby:myDB;create=true;user=user;password=pass";
try (
Connection connection = DriverManager.getConnection(DATABASE_URL, "user", "pass");
)
{
// ...
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
}
}
You can try if org.apache.derby.jdbc.EmbeddedDriver works. And it seems your connection url is wrong.
final String DATABASE_URL = "jdbc:derby://localhost:1527/myDB;create=true;user=user;password=pass";
Connection connection = null;
try{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
connection = DriverManager.getConnection(DATABASE_URL );
}
catch (Exception e)
{
e.printStackTrace();
}
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 am building a database connection scanner for my security course at university. I have used DriverManager.getConnection(connectionURL, username, password) and it seems to work fine but with one exception that I just cannot understand. If I enter the wrong username it is still returning a connection??? my test code is pasted below. Any pointers would be much appreciated. It returns the correct error if I put the wrong password in, if I turn the server off it tells me. But for some unknown reason it will not tell me if the username is wrong, its as if its not even checking!
public class DBConnector {
Connection connection = null;
String dbURL = "jdbc:mysql://localhost:3306";
String userName;
String password;
public DBConnector() {
// TODO Auto-generated constructor stub
}
public Connection tryConnection(String username, String password){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(dbURL, username, password);
System.out.println("Connected");
} catch (InstantiationException e) {
System.out.println("No Connection");
e.printStackTrace();
} catch (IllegalAccessException e) {
System.out.println("Connection Refused");
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Sql Ex");
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
}
And here is my main class to run the method.
public class MainTest {
public static void main(String[] args) {
DBConnector dbc = new DBConnector();
dbc.tryConnection("", "");
}
}
Maybe this has something to do with running the test on "Localhost"?
Thanks very much!
I would guess that you are logging in as an anonymous user.
You can make your local MySQL Server installation more secure (and hence force your code above to throw an error) by removing the anonymous user like this:
DELETE FROM mysql.user WHERE user='';
FLUSH PRIVILEGES;
Then try connecting with no username and password.
i'm trying to establish connection with mysql database through file properties and then run the information from servlet. my Connection class looks like this:
public class pageDao {
private Connection connection;
private Statement statement;
private pageDao() {
Properties prop = new Properties();
try {
//Class.forName("oracle.jdbc.driver.OracleDriver");
//Class.forName("org.gjt.mm.mysql.Driver");
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnfe) {
System.out.println("Error loading driver: " +cnfe);
}
try {
try {
//load a properties file
prop.load(new FileInputStream("config.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String db = prop.getProperty("database");
String dbuser = prop.getProperty("dbuser");
String dbpassword = prop.getProperty("dbpassword");
connection = DriverManager.getConnection(db,dbuser,dbpassword);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static pageDao thisDao;
public static pageDao gedDao()
{
if(thisDao == null)
thisDao = new pageDao();
return thisDao;
}
public PageData getPage(String id)
{
PageData data = new PageData();
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from pages where id='"+id+"'");
if(rs.next())
{
data.setId(rs.getString("id"));
data.setParentid(rs.getString("parentid"));
data.setTitle(rs.getString("title"));
data.setTitle4menu(rs.getString("title4menu"));
data.setKeywords(rs.getString("keywords"));
data.setDescription(rs.getString("description"));
data.setMaintext(rs.getString("maintext"));
}
else
return null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
when i run it, it doesn't show the mistake that connection wasn't established, but when it gets to the
public PageData getPage(String id) {
PageData data = new PageData();
try {
statement = connection.createStatement();
it throws java.lang.NullPointerException.
can anybody help me out with that?
there is no issue with code.
check your passing parameter ...
check sample
private Connection getConnection() {
try {
String dbUrl = "jdbc:mysql://localhost:3306/projectmining";
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(dbUrl, "root", "admin");
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
Is it possible to return the type Connection?
And use it as a method passed by reference through out the program?
I find it makes the database interaction a lot easier if it is passed as a method.
public static Connection database(String database, String username, String password) {
String url = "jdbc:postgresql:" + database;
//LOAD DRIVER
try {
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
//CONNECT TO DATABASE
try {
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
db = database("java_jdbc", "admin", "fake_password_1234");
}
You can do that.
Just remember to invoke close() on the connection to release its resources when done.
package mySystem;
import java.sql.*;
import javax.swing.*;
public class MySqlConnector {
Connection conn = null;
public static Connection ConnectDB() {
try {
Class.forName("com.mysql.jdbc.Driver"); //register jdbc driver
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/inventory_db", "root", "");
// JOptionPane.showMessageDialog(null, "Connected to db");
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}