I've got a little problem when I'm running my query.
This is my code:
try {
// Class.forName("com.mysql.jdbc.Driver");
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
} catch (Exception ex) {
// handle the error
System.out.println("Driver issue: " + ex.getMessage());
System.out.println("Driver issue: " + ex.getClass().toString());
}
try {
// Do something with the Connection
System.out.println("Connection: " + conn);
Statement stmt = conn.createStatement();
ResultSet RS = stmt.executeQuery("show slave status");
...
try {
conn = DriverManager.getConnection("jdbc:mysql://" + internetPort + ":" + port + "/", username, password);
System.out.println("Connected to: " + internetPort);
return;
} catch (SQLException e) {
I realized that the script is connecting to DB, then execute query but the result is empty. When I'm doing the same query on mysql console then I got 1 result (correct result) I've even changed query "show slave status" to "show processlist" and still nothing. What's more, on my PC it's working correctly and executing query with correct result, but on other PC it doesn't. user and password is correct (the same i logged in console). Could anyone help me with that?
Related
package main.java;
import java.sql.*;
public class SQLSetup {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/test_db";
// Database credentials
static final String USER = "Halli";
static final String PASS = "dragon";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
}
Why is CREATE TABLE REGISTRATION giving me the error "Unrecognized statement"? I am using Intellij, Java 13 and Maven and MySQL server.
This is just something to get my question through since the template is complaining about me not giving enough details and a lot of code, but I am not sure what more to say about the problem.
It did not even occur to me that I could run the code with Intellij giving me a red error on this, but it did not matter - I tried to run the code and Voila - it created a table, even with this error message.
When attempting to open a connection to a database it fails giving me a NullPointerException. This happens when it is trying to get the connection on the con = DriverManager.getConnection(url); line. It goes from this line to the catch exception. What is the correct way?
public void openDatabase () {
url = "jdbc:odbc:student";
try{
con = DriverManager.getConnection(url);
stmt = con.createStatement();
txtOutput.setText("Database " + url + " is connected\n");
}
catch (Exception e) {
txtOutput.setText("Problems connecting to " + url + "\n");
}
}
I have exhausted all avenues to sort out this problem, but to no avail. I have installed "SQL Management Studio 2012" and created a dummy database and methods, but I'm still getting a "null point exception pointer". Java and JDBC is set under user variables.
Here are the screen shots and code.
Static {
// standard code to open a connection and statement to SQL Server database
try {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://SQL-SERVER;"
+ "databaseName=ItunesDB;integratedSecurity=true;";
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
} // Handle any errors that may have occurred.
catch (SQLException sqle) {
System.out.println("Sql Exception :" + sqle.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("Class Not Found Exception :" + e.getMessage());
}
}
public static String listAll() {
String output = "";
try {
stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM LibraryTable");
while (res.next()) { // there is a result
// the name field is the thrid one in the ResultSet
// Note that with ResultSet we count the fields starting from 1
output += res.getString(1) + " " + res.getString(2) + " - "
+ res.getString(3) + " " + res.getString(4) + " "
+ res.getString(5) + "\n";
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return output;
}
public static String getName(String key) {
try {
SELECT * FROM LibraryTable WHERE key = '04'
stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM LibraryTable WHERE ID = '" + key + "'");
if (res.next()) { // there is a result
// the name field is the second one in the ResultSet
// Note that with ResultSet we count the fields starting from 1
return res.getString(2);
} else {
return null;
}
} catch (Exception e) {
System.out.println(e);
return null;
}`enter code here`
The database information:
Dummy Database
ID Name Artist Quantity Price Rating Playcount
What do I need to do to fix this?
Re install sql server in mixed mode . Then go to SQL Server configuration manager and checks is the TCP/Ip is enable . IF not enable it and restart the service. Then add sqljdbc jar in your project . Then try this code
Connection con = null;
try {
Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1433;"
+ "user=sa;password=HerongYang;"
+ "database=AdventureWorksLT");
}
user is always sa because it is the system administrator
When I do a insert in a remote tabke using jconnect it gives me the following error:
Unexpected exception : java.sql.SQLException: This transaction has been rolled back, rather than only the current statement.
, sqlstate = ZZZZZjava.sql.SQLException: This transaction has been rolled back, rather than only the current statement.
at com.sybase.jdbc4.jdbc.SybConnection.getAllExceptions(SybConnection.java:2780)
at com.sybase.jdbc4.jdbc.SybStatement.handleSQLE(SybStatement.java:2665)
at com.sybase.jdbc4.jdbc.SybStatement.nextResult(SybStatement.java:295)
at com.sybase.jdbc4.jdbc.SybStatement.nextResult(SybStatement.java:272)
at com.sybase.jdbc4.jdbc.SybStatement.updateLoop(SybStatement.java:2515)
at com.sybase.jdbc4.jdbc.SybStatement.executeUpdate(SybStatement.java:2499)
at com.sybase.jdbc4.jdbc.SybStatement.executeUpdate(SybStatement.java:577)
at connectSybase.main(connectSybase.java:48)
Do you know what it might be?
Here's my full code:
import java.io.*;
import java.sql.*;
public class connectSybase {
public static void main(String args[])
{
try
{
// jconn3 <-- do pessoal do OMS
//Class.forName("com.sybase.jdbc3.jdbc.SybDriver");
// jconn4 <-- do servidor de OMS1_PAR_DEV_SQL
Class.forName("com.sybase.jdbc4.jdbc.SybDriver");
}
catch (ClassNotFoundException cnfe)
{
System.out.println("BUM!");
}
try
{
System.out.println("Any of the following may throw an SQLException.");
System.out.println("Opening a connection.");
Connection con = java.sql.DriverManager.getConnection
("----------------------------");
// more code to use connection ...
System.out.println("Creating a statement object.");
Statement stmt = con.createStatement();
System.out.println("Executing the query.");
ResultSet rs = stmt.executeQuery("Select top 10 * from OMS_DEV..SCRIBE_AR");
System.out.println("Process the result set.");
while (rs.next())
{
System.out.println("Fetched value " + rs.getString(1));
}
System.out.println("Executing the query.");
int result = stmt.executeUpdate("---------------");
System.out.println("Process the result set: " + result );
}
catch (SQLException sqe)
{
sqe.printStackTrace();
System.out.println("Unexpected exception : " +
sqe.toString() + ", sqlstate = " +
sqe.getSQLState());
System.exit(1);
}
System.exit(0);
}
}
I've omitted the insert and the connection but both work because I get the result of the first select (only the insert fails) and the insert is also correct because it works using isql or dbartisan.
Sybase error message was not specific but the problem was related to packet size.
In ASE it was 8192 and in IQ only 2048.
It generated the error when the packet exceeded 2k.
I have a big question...
I have a database java program creation.
I want to know if the database exists or not, and the if exists just connect, if not to create it.
I tried this one:
if (dbName.exists() == false) {}
THIS IS ALL THE CODE...
Class.forName("com.mysql.jdbc.Driver");
System.out.println("MySQL JDBC driver loaded ok.");
THIS IS A BACKUP CODE FOR IT, JUST TO WORK FOR NOW....
PARTIAL CODE THAT WORKS !
conn = DriverManager.getConnection(DBurl + url
+ "?createDatabaseIfNotExist=true& + "
+ "useUnicode=true&characterEncoding=utf-8&user="
+ userName + "&&password=" + password);
System.out.println("Connected to database ");
System.out.println("Connected to the database " + url);
BUT I WANT SOMETHING LIKE:
FILE dbName = new FILE (url);
Statement stmt = new Statement;
if (dbName.exists() == true)
System.out.println("Database exists ! Connecting ... ");
else {
String sql = "CREATE DATABASE "+url;
stmt.executeUpdate (sql);
}
I don't want to put the url with the password and username in the same place... because they are provided from an external part, but that is allready implemented and working.
So I want to rip in 2 peaces, 1 Connect "jdbc:mysql://localhost:3306/"; WITHOUT URL which is the database NAME ...
AND THEN IF A DATABASE DOES NOT EXISTS THERE WITH THAT NAME JUST CREATE ON.
It is not working.... not entering in the else more, and says that Exeption Database already exists.
Thanks you very much.
If it is a MySQL database, the following code should work. Other databases may give a different error code, but the general way should be clear. Important is that you connect to the instance, not a specific database initially. For creating the tables, you will need to connect to the newly created database. You can't use the instance connection that I use in my example for creating the tables:
Connection connection = null;
Statement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost/",
"root", "admin");
statement = connection.createStatement();
String sql = "CREATE DATABASE DBNAME";
//To delete database: sql = "DROP DATABASE DBNAME";
statement.executeUpdate(sql);
System.out.println("Database created!");
} catch (SQLException sqlException) {
if (sqlException.getErrorCode() == 1007) {
// Database already exists error
System.out.println(sqlException.getMessage());
} else {
// Some other problems, e.g. Server down, no permission, etc
sqlException.printStackTrace();
}
} catch (ClassNotFoundException e) {
// No driver class found!
}
// close statement & connection
Without knowing much about what's going on here simply trying to connect to a database that doesn't exists should throw a TimeoutException error or something similar. Just catch the exception and do stuff if you cannot connect.
boolean canConnect = false;
Connection conn = null;
try{
conn = DriverManager.getConnection(...);
canConnect = true;
}(Exception ex){
canConnect = false;
}
if (!canConnect){
makeDatabase(...);
}
Enjoy your day!
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/", "root", "admin");
Statement statement = connection.createStatement();
String sql = "CREATE DATABASE IF NOT EXISTS DBNAME";
statement.executeUpdate(sql);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Kindly Note a Two things
The new driver class is `com.mysql.cj.jdbc.Driver'
The query CREATE DATABASE IF NOT EXISTS DBNAME means you dont have to check if database exits