Cannot create connection to database using jdbc - java

I am new to JDBC and using a tutorial to create my first connection. However, I am getting the below error -
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
import java.sql.*;
public class Demo {
public static void main(String[] args) throws Exception {
String url="jdbc:mysql://localhost:3306//demo";
String user="root";
String password="vishal123";
String query = "select * from student";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,user,password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
rs.next();
String name = rs.getString("user_name");
System.out.println(name);
st.close();
con.close();
}
}
Do let me know if you need any more details to solve the problem.

Related

Here I get an error when I pass my DB name i.e Test if I pass Sid it works

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getOracleConnection();
Statement stmt = null;
ResultSet rs = null;
stmt = conn.createStatement();
//only for Oracle
rs = stmt.executeQuery("select object_name from user_objects where object_type = 'TABLE'");
while (rs.next()) {
String tableName = rs.getString(1);
System.out.println("tableName=" + tableName);
}
stmt.close();
conn.close();
}
/*private static Connection getHSQLConnection() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
return DriverManager.getConnection(url, "sa", "");
}*/
/* public static Connection getMySqlConnection() throws Exception {
String driver = "org.gjt.mm.mysql.Driver";
String url = "jdbc:mysql://localhost/demo2s";
String username = "oost";
String password = "oost";
*/
/* Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
*/
public static Connection getOracleConnection() throws Exception {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:#localhost:1521:Test";
String username = "system";
String password = "root12345";
Class.forName(driver); // load Oracle driver
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
}
I'm going to get the list of tables from Test database but I'm getting the error like listener refused connection, Listener refused the connection with the following error as:
ORA-12505, TNS: listener does not currently know of SID given in connect descriptor
But when I change Test to Orcl then its working fine but I want to select the table from particular Database.
Where did I go wrong?
Best way to solve problem is first read the error or exception you got
ORA-12505, TNS: listener does not currently know of SID
In this error SID means In short the unique name of your DB.
When you're changing it test it simply means it does not available on current DB url
or that SID(DB) does not exists you need to create new with same name
or if SID is available then check your URL for that SID
edit 1:
To find SID you can use select * from global_name;
it will give you one value use it as it is .
I think you need to use test.world
make this changes to url
String url = "jdbc:oracle:thin:#localhost:1521/Test";
or
String url = "jdbc:oracle:thin:#localhost:1521/Test.world";

Sybase jdbc4 not returning any results from sql query

I'm trying to run a query against a Sybase database. It seems like the connection is made successfully but when it hits rs.next() it fails to go to the first row in the results. It jumps down to the rs.Close().
I know for a fact that my query below works. I'm running it in a sql tool and it returns one record.
Please can someone tell me what I'm doing wrong?
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;
import com.sybase.jdbc4.jdbc.SybDataSource;
import com.sybase.jdbc4.jdbc.SybDriver;
public class test {
public static void main(String[] args) throws SQLException {
SybDriver sybDriver = null;
Connection conn = null;
Statement stmt = null;
String host = "123.12.34.56";
String url = "jdbc:sybase:Tds:"+host+":1300";
String username = "testuser";
String password ="password";
try{
sybDriver=(SybDriver)Class.forName("com.sybase.jdbc4.jdbc.SybDriver").newInstance();
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select top 1 brand, model,color,serialnum from myTable order by newid()");
while(rs.next())
{
String one = rs.getString(1);
String two = rs.getString(2);
String three = rs.getString(3);
String four = rs.getString(4);
}
rs.close();
stmt.close();
conn.close();
} catch(SQLException | InstantiationException | IllegalAccessException | ClassNotFoundException ex) {
}
}

I'm trying to connect with Excel sheet using jdbc but I'm getting not a valid name exception

import sun.jdbc.odbc.*;
import java.sql.*;
class excelWorkBook
{
public static void main(String args[]) throws SQLException
{
JdbcOdbcDriver d = new JdbcOdbcDriver();
DriverManager.registerDriver(d);
Connection con = DriverManager.getConnection("jdbc:odbc:xdsn");
Statement st = con.createStatement();
String query = "SELECT * FROM [beers$]";
ResultSet rs = st.executeQuery(query);
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getInt(2)+" "+rs.getInt(3)+" "+rs.getInt(4)+" "+rs.getInt(5));
}
st.close();
con.close();
}
}
java.sql.Exception: [Microsoft][ODBC excel driver] beers$ is not a valid name.
I'm getting above exception while running the program

Java Derby Creating User and "Schema Does Not Exist" Error

I am writing some archiving program in Java using derby DB. My program and DB connections (creating table, inserting and selecting data etc.) working fine when i use default user "APP" of Derby now.
When i try add some users and changing DB Properties, i can't connect to Database. I am sharing my User Creating and Changing DB Properties class below;
Creating user and Setting DB Properties:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateUser {
public static void main(String[] args) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
String connectionUrl = "jdbc:derby:sampleDB;user=APP;password=APP";
Connection con = null;
Statement stmt = null;
con = DriverManager.getConnection(connectionUrl);
stmt = con.createStatement();
stmt.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.connection.requireAuthentication', 'true')");
stmt.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.authentication.provider', 'BUILTIN')");
stmt.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.user.testuser', 'ajaxj3x9')");
stmt.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.database.fullAccessUsers', 'testuser')");
stmt.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.database.propertiesOnly', 'false')");
stmt.close();
con.close();
boolean gotSQLExc = false;
try {
DriverManager.getConnection("jdbc:derby:;shutdown=true");
} catch (SQLException se) {
if ( se.getSQLState().equals("XJ015") ) {
gotSQLExc = true;
}
}
if (!gotSQLExc) {
System.out.println("Database did not shut down normally");
} else {
System.out.println("Database shut down normally");
}
}
}
After that when i use below statement to connect DB i receive java.sql.SQLSyntaxErrorException: Schema 'TESTUSER' does not exist error
java.sql.Statement stmt = null;
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
String connectionUrl = "jdbc:derby:sampleDB;create=false;user=testuser;password=ajaxj3x9";
con = DriverManager.getConnection(connectionUrl);
stmt = con.createStatement();
Also i have tried CREATE SCHEMA AUTHORIZATION testuser after all creating and properties defined in CreateUser class (sure i have rollback first creation proccess before trying this and run same Creating process after adding this line) but when i try same statement i receive TESTTABLE Schema Not Exist error this time.

inserting values into mysql table using jdbc

Values inserted using program are not seen in database. the following is the code which I used for the same
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JDBC {
private static Scanner sc;
public static void main(String args[]) throws Exception {
sc = new Scanner(System.in);
System.out.println("hii");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/rsystems", "root", "rsystems");
PreparedStatement stmt = con.prepareStatement("insert into user valiues(?,?)");
System.out.println("Enter id:");
int no = sc.nextInt();
System.out.println("Enter name:");
String name = sc.next();
stmt.setInt(1, no);
stmt.setString(2, name);
//I think I need to commit over here and I have tried the same but even with that I didn't see my inserted data in database
}
}
You've wrong query in your PreparedStatement
PreparedStatement stmt = con.prepareStatement("insert into user (id, name) values(?,?)");
You query is wrong and you are never executing it.
PreparedStatement stmt = con.prepareStatement("insert into user values(?,?)");
stmt.execute();
Maybe you can use try..catch help you to find the mistake you make just a wrong word
You are not executing your query inside preparedStatement. Also make sure you have valid SQL.
You can use PreparedStatement.executeUpdate()
Executes the SQL statement in this PreparedStatement object, which must be an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE; or an SQL statement that returns nothing, such as a DDL statement.
Try
PreparedStatement stmt = con.prepareStatement("insert into user values(?,?)");
stmt.executeUpdate();
From maintenance point of view, we specify order of columns in insert query like.
insert into user (id, name) values(?,?)
Commit:
You can check your database configuration about autoCommit. If by default autoCommit is true then you can omit commiting in your code else you will have to commit it manually in your code. Like
con.commit();
Connection close:
You should close your statements and connection when they are no longer required.
stmt.close();
connection.close();
Note: Don't forget to handle/throw Exceptions throws from all these methods such as SQLException.
public static void main(String args[]) {
String dbURL = "jdbc:mysql://localhost:3306/student";
String username = "root";
String password = "root";
try {
Connection conn = DriverManager.getConnection(dbURL, username, password);
if (conn != null) {
System.out.println("Connected");
}
String sql = "INSERT INTO Users (id, password,) VALUES (?, ?)";
PreparedStatement statement;
statement = conn.prepareStatement(sql);
statement.setInt(1, 1);
statement.setString(2, "admin");
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A Record inserted successfully!");
}
} catch (SQLException e) {
System.out.println("Exception occured" + e);
}
}
After setting value need PreparedStatement executed
Look at below
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
public class JDBC {
private static Scanner sc;
public static void main(String args[]) throws Exception {
sc = new Scanner(System.in);
System.out.println("hii");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/rsystems", "root", "rsystems");
PreparedStatement stmt = con
.prepareStatement("insert into user valiues(?,?)");
System.out.println("Enter id:");
int no = sc.nextInt();
System.out.println("Enter name:");
String name = sc.next();
stmt.setInt(1, no);
stmt.setString(2, name);
stmt.execute();//You have to execute this statement
// I think I need to commit over here and I have tried the same but even
// with that I didn't see my inserted data in database
}
}
This works:
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JDBC {
private static Scanner sc;
public static void main(String args[]) throws Exception {
sc = new Scanner(System.in);
System.out.println("hii");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/rsystems", "root", "rsystems");
PreparedStatement stmt = con.prepareStatement("insert into user values(?,?)");
System.out.println("Enter id:");
int no = sc.nextInt();
System.out.println("Enter name:");
String name = sc.next();
stmt.setInt(1, no);
stmt.setString(2, name);
stmt.executeUpdate();
}
}

Categories