Error in connect to SQL Server 2008 R2 using JDBC - java

I am using Java to connect Microsoft SQL Server 2008 R2 and sqljdbc4.jar, but there is a problem with the initial connection. After running, 3 is displayed in the browser only.
This is my code:
import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
public class Database {
static Connection con = null;
public static int dbConnect() {
int x = 3;
try {
// Establish the connection.
SQLServerDataSource ds = new SQLServerDataSource();
ds.setIntegratedSecurity(true);
ds.setServerName("172.18.16.10");
ds.setPortNumber(1433);
ds.setDatabaseName("my-database");
ds.setUser("my-user");
ds.setPassword("my-pass");
con = ds.getConnection();
x = 5;
if (con != null) {
x = 1;
}else{
x = 0;
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return x;
}}
and this is the error I receive:
Login failed. The login is from an untrusted domain and cannot be used
with Windows authentication.
ClientConnectionId:af711e9c-941f-4535-9ccb-b6ef31a42fdf
The older questions about my problem in SO were not helpful for me. I added sqljdbc-auth.jar into /java/bin and path also in /java/lib

I add sqljdbc.jar and import that :
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.microsoft.sqlserver.jdbc.*;
I define all need variable in Global ans Static :
private static SQLServerDataSource ds = null;
private static Connection con = null;
and define a method for connect:
public static boolean getConnection() {
try {
System.out.println(ServerName);
ds = new SQLServerDataSource();
ds.setServerName(ServerName);
ds.setPortNumber(1433);
ds.setDatabaseName(DatabaseName);
ds.setUser(UserName);
ds.setPassword(Password);
con = ds.getConnection();
if (con != null) {
System.out.println("Success");
}
stmt = con.createStatement();
return true;
} // Handle any errors that may have occurred.
catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
}

Try doing something like this.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Database {
static Connection con = null
public static int dbConnect() {
int x = 3;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://172.18.16.10:1433;databaseName=my-database;user=my-user;password=my-pass;");
x = 5;
if (con != null) {
x = 1;
}else{
x = 0;
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return x;
}
}
You will get a proper connection using the above code.
Morever, the driver Name ("com.microsoft.sqlserver.jdbc.SQLServerDriver") and the connection url should always be read from a config file. Try taking the above two things out of your code into a config file.

Related

No suitable driver found error even if the my-sql connector uploaded into the library

I am new to java and in a learning process. I'm working on connecting my JDE with MySql and I have followed every step necessary. but when I run the code, I got " No suitable driver found for jdbc.mysql://localhost:3306/dbname" error. I reviewed questions already in stackoverflow and other sources; but the provided solution didn’t work for me.
Any suggestions why i got this error even if I uploaded the mysql-connector-j-8.0.31/mysql-connector-j-8.0.31.jar.a screenshot of my code and the error message
package JDBC;
import java.sql.SQLException;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.Connection;
public class JDBC {
public static void main(String[] args) throws SQLException{
String url = "jdbc.mysql://localhost:3306/University";
String username = "root";
String password = "root";
String query = "select * from EngineeringStudents";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
}catch(ClassNotFoundException e) {
//To do auto-generated catch block
e.printStackTrace();
}
try {
Connection con = DriverManager.getConnection(url, username, password);
Statement statement = con.createStatement();
ResultSet result = statement.executeQuery(query);
while(result.next()) {
String UniversityData = "";
for(int i = 1; i <= 6; i++) {
UniversityData += result.getString(i) + ":";
}
System.out.println(UniversityData);
}
}catch(SQLException e) {
e.printStackTrace();
}
}
}
Bro use String url = "jdbc:mysql://localhost:3306/University". Use have missed a colon ':' after jdbc instead you're using '.'

Apache DBCP and Oracle Transparent Application continuity

We have an older application that can't failover when one node of our Oracle RAC goes down. It seems it uses an older version of org.apache.commons.dbcp.BasicDataSource. I can make this work when I use UCP from Oracle but when I use the apache version the app dies as soon as I shut down the node of the RAC it is connected to. Am I missing something or does it not work with Apache DBCP? Thanks
Here is my code.
import org.apache.commons.dbcp.BasicDataSource;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BasicDB{
final static String DB_URL ="jdbc:oracle:thin:user/password#pdb_tac";
final static String driverClassName = "oracle.jdbc.replay.OracleDataSourceImpl";
private void pressAnyKeyToContinue()
{
System.out.print("Press any key to continue...");
try { System.in.read(); }
catch(Exception e) { e.printStackTrace(); }
}
public String getInstanceName(Connection conn) throws SQLException {
PreparedStatement pstmt = conn.prepareStatement("select instance_name from v$instance");
String r = new String();
for(ResultSet result = pstmt.executeQuery(); result.next(); r = result.getString("instance_name")) {
}
pstmt.close();
return r;
}
private void doTx(Connection c, int numValue) throws SQLException {
String updsql = "UPDATE test SET v=UPPER(v) WHERE id=?";
PreparedStatement pstmt = null;
pstmt = c.prepareStatement(updsql);
c.setAutoCommit(false);
for(int i = 0; i < numValue; ++i) {
pstmt.setInt(1, i);
pstmt.executeUpdate();
}
c.commit();
pstmt.close();
}
public static void main(String[] args) throws SQLException {
Connection conn = null;
int numValue = 5000;
;
try {
BasicDataSource bods = new BasicDataSource();
bods.setUrl(DB_URL);
bods.setDriverClassName(driverClassName);
bods.setDefaultAutoCommit(false);
BasicDB self = new BasicDB();
conn = bods.getConnection();
String var10001 = self.getInstanceName(conn);
var10000.println("Instance Name = " + var10001);
System.out.println("Performing transactions");
self.pressAnyKeyToContinue();
self.doTx(conn, numValue);
var10001 = self.getInstanceName(conn);
var10000.println("Instance Name = " + var10001);
} catch (Exception var8) {
var8.printStackTrace();
}
}
}
Ok, so it has to do with using the DataSource instead of the DataDriver class. I have run into another error so will create a new question for that.

SQL connection busy although it's already closed

My SQL connection keeps saying it's busy even though all previous connections are closed.
The error below results. All others are either closed by the exiting of the JFrame or the .close() method. Does anyone see anything wrong with the class? (All other classes work as intended.)
SEVERE: null
org.sqlite.SQLiteException: [SQLITE_BUSY] The database file is locked (database is locked)
at org.sqlite.core.DB.newSQLException(DB.java:941)
at org.sqlite.core.DB.newSQLException(DB.java:953)
at org.sqlite.core.DB.execute(DB.java:854)
at org.sqlite.core.DB.executeUpdate(DB.java:895)
package teacherreviewproject;
//initialise imports
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class FeedbackForm extends javax.swing.JFrame {
//init. variables
String WWW;
String EBI;
int rating;
String teacher;
String studentUser;
String ratingraw;
String teacherQuery;
public FeedbackForm(String s) {
initComponents();
getTeachersNames();
this.studentUser = s;
}
private void getTeachersNames(){
//get the connection
Connection con = DBConnection.getConnection();
//set up query string
this.teacherQuery = "SELECT * FROM users WHERE type=2";
try {
//prepare statement
PreparedStatement teacherState = con.prepareStatement(teacherQuery);
//execute query
ResultSet teachResult = teacherState.executeQuery();
//clear previous items to avoid duplicates.
jComboBox_teachers.removeAllItems();
//create counter variable to get different teachers in RS
int i = 0;
//while loop
while(teachResult.next()){
//get username then add it to position i at combobox
String tempOption = teachResult.getString("username");
System.out.println(tempOption);
jComboBox_teachers.addItem(tempOption); //thanks mcalpine
//increment i
i++;
}
} catch (SQLException ex) {
Logger.getLogger(FeedbackForm.class.getName()).log(Level.SEVERE, null, ex);
}
Found the bug! I needed to make a close-if feature on my Connection class.
Here's the code, should anyone want it:
public class DBConnection{
public static Connection con = null;
public static Connection getConnection(){
//initialise connection
try{
//creates valid url to access DB with
String url = "jdbc:sqlite:" + System.getProperty("user.dir") + "/TeacherReviewIA.DB";
if(con == null){
con = (Connection) DriverManager.getConnection(url);
}else{
con.close();
con = (Connection) DriverManager.getConnection(url);
}
//as a debug measure and to show connection given
System.out.println(con);
}
catch(SQLException ex){
JOptionPane.showMessageDialog(null,ex,"WARNING",JOptionPane.WARNING_MESSAGE);
}
//allows code that called method to use connection given
return con;
}
}

Can't connect to SOCKS proxy:Connection refused: connect

I'm getting the following error. Check many solutions but didn't get the result.
Not Connected to the database - networkcoding
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
ERROR: java.lang.NullPointerException
The last packet sent successfully to the server was 0 milliseconds ago.
The driver has not received any packets from the server.
The following is the database connection code.
public class DBConnect {
// System.out.println("MySQL Connect Example.");
public static Connection getConnection() {
Connection conn = null;
String url = "jdbc:mysql://127.0.0.1:3306/";
String dbName = "networkcoding";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "xampp123";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
System.out.println("Connected to the database "+dbName);
//conn.close();
//System.out.println("Disconnected from database");
} catch (Exception e) {
System.out.println("Not Connected to the database - "+dbName);
e.printStackTrace();
}
return conn;
}
public static void main(String arg[]){
DBConnect.getConnection();
}
}
The error is within the following part of the code:
package privacysensor;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import javax.swing.JOptionPane;
public class Sensors extends javax.swing.JFrame {
/**
* Creates new form Sensors
*/
String s1 = "", s2 = "", s3 = "", s4 = "", s5 = "", s6 = "", s7 = "", s8 = "", s9 = "";
DBConnect c = new DBConnect();
DateFormat df = new SimpleDateFormat("hh:mm a");
Calendar cal1 = Calendar.getInstance();
org.jdesktop.application.ResourceMap resourceMap =
org.jdesktop.application.Application.getInstance(
privacysensor.PrivacySensorApp.class).getContext().getResourceMap(Sensors.class);
Class1 x = new Class1();
int id, id1;
public Sensors() {
initComponents();
try {
id = x.idgeneration();
id1 = x.Tidgeneration();
Connection c1 = c.getConnection();
Connection c2 = c.getConnection();
PreparedStatement pst = c1.prepareStatement("update sensors set status='Offline' where id=" + id);
int s = pst.executeUpdate();
if (s == 0) {
System.out.println("Not updated");
} else {
System.out.println("Updated");
}
PreparedStatement pst1 = c2.prepareStatement("update timing set status='Offline' where id=" + id1);
s = pst1.executeUpdate();
if (s == 0) {
System.out.println("Timer updated");
} else {
System.out.println("TImer not updated");
}
} catch (Exception e) {
System.out.println(e);
}
... // End of variables declaration
}
}
Any suggestions are welcome. Thank you,
I use mac OS X and I got the error:
Can't connect to SOCKS proxy:Connection refused: connect.
I opened:
System Preferences -> Network -> Advanced ->Proxy -> unchecked SOCKS proxy
This resolved the problem.
In the stack trace, I got the error Can't connect to SOCKS proxy:Connection refused: connect
I figured it was because of the system proxy settings, the connection was refused. Remove the proxy and it will work like a charm. To remove proxy settings in Windows 10,
Open Settings - Click Network & Internet - Click Proxy
In Manual Proxy Setup, uncheck Use a proxy server
Thank you all.

Mysql database Exception

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from java.sql.Statement to com.mysql.jdbc.Statement
i am a beginner in java i am trying to use mysql database i have downloaded mysql-connector-java-5.1.23-bin.jar file from mysql.com and i have added this jar file to in my build path of my project but there is an error in the following code
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from java.sql.Statement to com.mysql.jdbc.Statement
package com.example.demo;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class DBConnect
{
private static final String userName = "root";
private static final String userpwd = "sverma";
private static final String CONN_STR = "jdbc:mysql://localhost:3306/phpweb_db";
public static void main(String[] args) throws SQLException
{
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try
{
DriverManager.getConnection(CONN_STR, userName, userpwd);
st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery("select * from user");
rs.last();
System.out.println("No of rows: " + rs.getRow());
// System.out.println("Connected Successfully...");
}
catch (SQLException e)
{
System.err.println(e);
}
finally
{
if (rs != null)
{
rs.close();
}
if (st != null)
{
st.close();
}
if (conn != null)
{
conn.close();
}
}
}
}
Wrong classes
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
should be
import java.sql.Connection;
import java.sql.Statement;
In fact, java decouples everything from a specific database engine. One never should need an import of MySQL (or ProgressSQL or ...) classes.
To have those classes available at run-time, the first thing after the try, before getting the connection would be:
Class.forName("com.mysql.jdbc.Driver");
This technique would allow reading all strings from a configuration file, and writing database independent code.
Missing: conn = ...
conn = DriverManager.getConnection(CONN_STR, userName, userpwd);
package com.example.demo;
import java.sql.*;
public class DBConnect
{
private static final String userName = "root";
private static final String userpwd = "sverma";
private static final String CONN_STR = "jdbc:mysql://localhost:3306/phpweb_db";
public static void main(String[] args) throws SQLException
{
Connection conn;
Statement st;
ResultSet rs;
try
{
Class.forName("com.mysql.jdbc.Driver");
DriverManager.getConnection(CONN_STR, userName, userpwd);
st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery("select * from user");
rs.last();
System.out.println("No of rows: " + rs.getRow());
// System.out.println("Connected Successfully...");
}
catch (SQLException e)
{
System.err.println(e);
}
finally
{
if (rs != null)
{
rs.close();
}
if (st != null)
{
st.close();
}
if (conn != null)
{
conn.close();
}
}
}

Categories