Please look at the following code for a MSSQL Server 2005.
Properties File
driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://127.0.0.1:1433;databaseName=LibMgmtSys
user=sa
password=passwrod
Connection File
public class DBConnection {
static Properties dbproperties;
public static Connection getConnection() throws Exception {
Connection conn = null;
InputStream dbInputStream = null;
dbInputStream = DBConnection.class.getResourceAsStream("jdbc.properties");
try {
dbproperties.load(dbInputStream);
Class.forName(dbproperties.getProperty("driver"));
conn = DriverManager.getConnection(dbproperties.getProperty("url"),
dbproperties.getProperty("user"),
dbproperties.getProperty("password"));
} catch (Exception exp) {
System.out.println("error : " + exp);
}
return conn;
}
}
The above code gives me a NullPointException when I try to do dbproperties.load(dbInputStream). Am I doing something wrong???
You didn't instantiate dbproperties, so it's null when you try to dereference it (dbproperties.load(dbInputStream);). Change it to:
try {
dbproperties = new Properties();
dbproperties.load(dbInputStream);
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();
}
Here's my Code:
public static Connection connectToDataBase() throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (final Exception e) {
throw new RuntimeException("Driver failure");
}
connectionProperties = new Properties();
connectionProperties.put("user", user);
connectionProperties.put("password", passwor);
datenbankverbindung = DriverManager.getConnection(link, connectionProperties);
return connection;
}
I'm connecting to the database, which works fine. But I want to know whether the login data are false or if there's a problem with the connection.
Please read this
It says that DriverManager.getConnection throws SQLException. So you can catch this exception like:
try{
...
datenbankverbindung = DriverManager.getConnection(link,connectionProperties);
}catch(SQLException e){
...//do whatever you want
}
Hope this helps.
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 having the following problem. I'm using Java properties to read some info of a file, but when I call prop.getProperty("var") it returns null. I ran out of ideas. Here is the code I have.
static final Properties prop = new Properties();
public JConnection(){
try{
prop.load(new FileInputStream("db.properties"));
}catch(Exception e){
logger.info("file not found.");
e.printStackTrace();
}
}
I never get the error message "file not found".
public static Connection getConnection(String conType) {
Connection conn;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
if(model == "client"){
conn = DriverManager.getConnection(prop.getProperty("url"),prop.getProperty("usr"),prop.getProperty("pass"));
}else{
conn = DriverManager.getConnection(prop.getProperty("url1"),prop.getProperty("usr1"),prop.getProperty("pass1"));
}
} catch (Exception ex) {
ex.printStackTrace();
conn = null;
}
When it tries to connect to the DB, getProperty is returning null as it is not found. Any ideas of what it could be or what I'm doing wrong?
Another wild guess: I noticed that both your prop variable and the method that's reading from it are static, so maybe you are using this as some sort of static utilities class without ever creating an instance of the class? In this case, you are never calling the constructor and never actually loading the properties file. Instead, you might try this:
static final Properties prop = new Properties();
static {
try{
prop.load(new FileInputStream("db.properties"));
}catch(Exception e){
logger.info("file not found.");
e.printStackTrace();
}
}
You have a static field (prop), but you initialize it in a constructor. This means if you consult your prop object before you construct any object of JConnection, prop will not be initialized.
You can try something like this:
public class JConecction {
static final Properties prop = new Properties();
static {
try {
prop.load(new FileInputStream("db.properties"));
} catch(Exception e) {
logger.info("file not found.");
e.printStackTrace();
}
}
}
I’m trying to connect a Java program with MS SQL SERVER 2012 but Java throws the exception: java.lang.ClassNotFoundException.
I understand that the problem often is a result of that the CLASSPATH is not set up correctly for the driver. I have followed the directions from Oracle to add a CLASSPATH, but I still get the same exception. When I type “echo %CLASSPATH%" in the command prompt I get a correct response. What have I missed?
Code:
import java.sql.*;
public class JDBCTest {
public static void main(String[ ] args) throws SQLException {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch(Exception e) {
System.out.println("Can't find database driver: " + e);
}
}
}
The runtime environment for your application may not contain the appropriate jar file.
The path that you have checked is only for your console environment. The application classpath is different from this.
Try this
public class connectURL {
public static void main(String[] args) {
// Create a variable for the connection string.
String Connectionurl="jdbc:sqlserver://localhost:1433;DatabaseName=YourDBName;user=UserName;Password=YourPassword"
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
String SQL = "";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
....
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
make sure that you download the driver jar file and put it at the right place
If Class.forName fails it is a problem of classpath.
try this code to check your classpath:
String classPath = System.getProperty("java.class.path");
String userDir = System.getProperty("user.dir");
System.out.println("Working Directory:");
System.out.println("\t"+userDir);
System.out.println("Classpath:");
String[] paths = classPath.split(";");
for (String path : paths) {
File pathFile = new File(path);
String check = pathFile.exists()?"OK ":"NOT-FOUND ";
System.out.println("\t"+check+path);
}
First of all download sqljdbc4.jar from here
Put this .jar in Your /WEB-INF/lib folder. (Check if this file appears from your eclipse's lib if not then Refresh Your Project)
And then run Your Project.