ODBC Connection Error using Stored Procedure in Netbeans - java

I am making an inventory management program. The Problem is I am using multiple SQL queries with stored procedure. Which is something like this:
try
{
CallableStatement c= m.XC.prepareCall("{call addCategory_Combobox}");
ResultSet rs = c.executeQuery();
while(rs.next())
{
String name = rs.getString("category");
jComboBox2.addItem(name);
}
rs.close();
c.close();
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
Here is connection I have made so far:
public class MyConnection
{
Connection XC;Statement ST;
public MyConnection()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
XC=DriverManager.getConnection("jdbc:odbc:signupcon", "sa", "123");
ST=XC.createStatement();
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
The problem is that when I run the code for the 1st time, it executes successfully. But when I run the same code for the second time. it get the following Error:java.sql.SQLException: [Microsoft][ODBC SQL Server Driver]Connection is busy with results for another hstmt
and here is the SQL Query Code:
create proc addCategory_Combobox
as
begin
Declare #Status varchar(max)
select category from Category
SELECT #Status as result
end
go

Related

IJ can't find driver for JDBC

I'm sorry for my question but can't solve this problems myself. Read different topics here and tried to read tutuorials...
I have MySQL server v8, and trying to start simple example in java to get data from server.
I set up classpat as system variable, put here mysql-connector-java-8.0.13.jar. Comman echo %CLASSPATH% shows it properly. Also i put connector in all project folders xD (didn't help either).
import java.sql.*;
public class file_test {
// JDBC URL, username and password of MySQL server
private static final String url = "jdbc:mysql://localhost:3306/MySQL80";
private static final String user = "root";
private static final String password = "123";
// JDBC variables for opening and managing connection
private static Connection con;
private static Statement stmt;
private static ResultSet rs;
public static void main(String args[]) {
String query = "select count(*) from actor";
try {
// opening database connection to MySQL server
con = DriverManager.getConnection(url, user, password);
// getting Statement object to execute query
stmt = con.createStatement();
// executing SELECT query
rs = stmt.executeQuery(query);
while (rs.next()) {
int count = rs.getInt(1);
System.out.println("Total number of actors in the table : " + count);
}
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
} finally {
//close connection ,stmt and resultset here
try {
con.close();
} catch (SQLException se) { /*can't do anything */ }
try {
stmt.close();
} catch (SQLException se) { /*can't do anything */ }
try {
rs.close();
} catch (SQLException se) { /*can't do anything */ }
}
}
}
Problem is when i try to start projest, IJ says:
"C:\Program Files\Java\jdk-11.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA\lib\idea_rt.jar=63236:C:\Program Files\JetBrains\IntelliJ IDEA\bin" -Dfile.encoding=UTF-8 -classpath F:\work\program\file_test\out\production\file_test file_test
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/MySQL80
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at file_test.main(file_test.java:21)
Exception in thread "main" java.lang.NullPointerException
at file_test.main(file_test.java:38)
Process finished with exit code 1
I want to run this code from IJ and get data from DB as a result.

Error when trying to add new data to one of my tables

Working on a project where I have to add new data to different tables (i'm new at this). I'm using Netbeans which is connected to a mysql database. The database is working fine and my queries work when I execute them directly. But when I try to update the tables with new data through my javacode, it fails.
Code:
ConnectionClass db = new ConnectionClass();
try {
db.ConnectToDb();
} catch (SQLException ex) {
Logger.getLogger(AddUser.class.getName()).log(Level.SEVERE, null, ex);
}
String sql = "insert into users values (3, 'Nicklas', 'niklas#alskart.se', 'nisun', 'heej', '1')";
/* String laggTill = "insert into agent values ("+idb.getAutoIncrement("agent", "aid")+
", '"+tfNamn.getText()+"', '"+tfNr.getText()+"', '"+tfMail.getText()+"')";
*/
try {
db.myStmt.executeUpdate(sql);
} catch (SQLException ex) {
Logger.getLogger(AddUser.class.getName()).log(Level.SEVERE, null, ex);
}
}
Exception Generated:
apr 10, 2015 1:17:47 EM Project.AddUser btn_saveNewUserActionPerformed
ALLVARLIG: null
java.sql.SQLException: No operations allowed after statement closed.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:937)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:872)
at com.mysql.jdbc.StatementImpl.checkClosed(StatementImpl.java:445)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1554)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1549)
at Project.AddUser.btn_saveNewUserActionPerformed(AddUser.java:159)
Hi see your stacktrace is says
java.sql.SQLException: No operations allowed after statement closed.
means Statement object is not there.
your can do it in following way:
Statement myStmt;
try {
myStmt = db.createStatement();
myStmt.executeUpdate(sql);
} catch (SQLException ex) {
Logger.getLogger(AddUser.class.getName()).log(Level.SEVERE, null, ex);
}
i assume that reference variable db is of type Connection.
The basic steps when inserting data record to database are:
Connection connection //connect to db
PreparedStatement statement;
String query = "INSERT INTO...";
statement = connection.prepareStatement(query); //prepareStement (or createStatement()) based on query
statement.executeUpdate();
I think you missed the prepareStatement() or createStatement() step.
So (I do not know what you ConnectionClass looks like, please publish it):
try {
db.myStmt.createStatement();
db.myStmt.executeUpdate(sql);
} catch (SQLException ex) {
Logger.getLogger(AddUser.class.getName()).log(Level.SEVERE, null, ex);
}
At the end you must close connection and statement.
Working example: http://www.mkyong.com/jdbc/jdbc-statement-example-insert-a-record/

SQL, JDBC "Invalid column index" error with simple query

I'm new to STRUTS and JDBC, my application tries to connect to a simple DB that has 3 tables, right now all is doing is trying to query 1 table that only stores "first, last names and a Id field"
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return null;
}
System.out.println("Oracle JDBC Driver Registered!");
try {
connection =
DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","david","changeit");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return null;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
where I would like to get the result of 1 column if a match occurs:
String sql = "SELECT S_ID FROM Students WHERE firstname=? AND lastname=?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, firstname);
ps.setString(2, lastname);
rs = ps.executeQuery();
while (rs.next()) {
studentid = rs.getString(1);
ret = SUCCESS;
}
} catch (Exception e) { ...
As far as I can tell the connection is made,
the SQL query
Select s_id from Students where firstname='first' and lastname='last';
when run on SQL Dev. works and gives me a single result.
I don't really get a stack trace the code just jumps from right before the 'while (rs.next()) {..' directly into the finally block
} catch (Exception e) {
e.printStackTrace();
ret = ERROR;
} finally {
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
}
}
}
I'm not sure how Oracle drivers work. But below statement is what i see on Oracle site. Are you getting a non empty resultset ?
As you are not getting a nullpointerexception on .next(), i'm wondering if Oracle drivers return an empty ResultSet, which may lead to this problem.
http://docs.oracle.com/cd/B28359_01/java.111/b31224/getsta.htm
In case of a standard JDBC driver, if the SQL string being executed
does not return a ResultSet object, then the executeQuery method
throws a SQLException exception. In case of an Oracle JDBC driver, the
executeQuery method does not throw a SQLException exception even if
the SQL string being executed does not return a ResultSet object.
Like I said I'm new at using this.
The problem was that my schema didn't have the CONNECT role assigned to it.
Solution log in as 'SYSTEM' and grant the role to my schema
grant connect to MY_SCHEMA;

MYSQL select gets deleted values (JAVA)

I have a mysql database on my ubuntu server. When i delete rows with MYSQL workbench on this database and than try to select these rows with my Java program, i still get the deleted rows. (I have committed the command with MYSQL workbench)
In my java program I access the database over a Java Restful webservice which also runs on my server.
my webservice looks like:
#Path("/getAll")
#GET
#Produces({MediaType.APPLICATION_XML})
public List<PV> getAllPV() {
List<PV> ret =null;
try {
ret=Database.getInstance().getAllPV();
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
My Database:
public List<PV> getAllPV() throws Exception{
Connection conn = null;
PreparedStatement ps=null;
Statement s = null;
conn = getDBConnection();
conn.setAutoCommit(false);
List<PV> ret = new ArrayList<PV>();
s = conn.createStatement();
ResultSet rs = s.executeQuery("select * from PV");
...
conn.close();
}
Has anyone an idea ?

java.sql.SQLException: No database selected - why?

the last days I was trying to learn how to access mySQL databases via Java.
I am able to load the driver and get a connection to the database ( at least I think so, since I don't get an exception there..)
the code is:
import java.sql.*;
public class test
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("driver loaded...");
}
catch(ClassNotFoundException e){
System.out.println("Error in loading the driver..."+e);
System.exit(0);
}
try
{
Connection dbConnection= DriverManager.getConnection("jdbc:odbc:test","root","password");
System.out.println("Connection successful...");
Statement stmt = dbConntection.createStatement();
stmt.executeUpdate("create table Accounts ( name char(20) )");
}
catch(SQLException e)
{
System.out.println("database-ConnectionError: "+e);
System.exit(0);
}
}
}
When I execute it, it says:
driver loaded... Connection successful...
database-ConnectionError: java.sql.SQLException: [MySQL][ODBC 5.2(w) Driver][mysqld-5.5.31]No database selected
I really don't know the problem, because I thought the database is selected during the "getConnection" process....
I tried to select a database by adding this line:
stmt.executeUpdate("use test;");
after creating the Statement.
unfortunately it didn't work because I got another exception which said I should check on the syntax. I don't understand that either because in my commandline it works just fine...
I don't know if it is possible to use these type of commands via Java so if it isn't, please forgive my mistake.
I hope you can help me and I didn't miss the solution during my own search!
Already Thanks to all who reply and use their time on my problems!
ps. If I forgot to point out some important infos ( I don't think i did) please ask:)
edit: I also tried to create a new database during runtime
stmt.executeUpdate("CREATE DATABASE test;");
this actually works, but the database won't be selected either...
Before you can add a table, you first have to select a database.
you can create a new database with:
CREATE DATABASE database_name
you can connect to a specific database with:
String url = "jdbc:mysql://localhost/databasename";
String username = "test";
String password = "test";
Connection connection = DriverManager.getConnection(url, username, password);
Firstly, I am considering my answer to show you another better way for connection with MySQL Database, it's much easier and less nu-expected Exception(s).
You need to do some steps:
Download Connector/J and add it to your class path(if you are using an IDE there is add the .jar to the library, or there is many tuts on YouTube).
Create your database in your MySQL program.
See this example below example below I made for you demonstrates how to connect and execute queries on MySQL :
import java.sql.*;
public class MySqlConnection {
private String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
private String MYSQL_URL = "jdbc:mysql://localhost:3306/test";
private Connection con;
private Statement st;
private ResultSet rs;
public MySqlConnection() {
try {
Class.forName(MYSQL_DRIVER);
System.out.println("Class Loaded....");
con = DriverManager.getConnection(MYSQL_URL,"","");
System.out.println("Connected to the database....");
st = con.createStatement();
int c =st.executeUpdate("CREATE TABLE Accounts (Name VARCHAR(30))");
System.out.println("Table have been created.");
System.out.println(c+" Row(s) have been affected");
con.close();
} catch(ClassNotFoundException ex) {
System.out.println("ClassNotFoundException:\n"+ex.toString());
ex.printStackTrace();
} catch(SQLException ex) {
System.out.println("SQLException:\n"+ex.toString());
ex.printStackTrace();
}
}
public static void main(String...args) {
new MySqlConnection();
}
}
Here is your updated example, which works for me.
public static void main(String[] args) throws InstantiationException,
IllegalAccessException {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("driver loaded...");
} catch (ClassNotFoundException e) {
System.out.println("Error in loading the driver..." + e);
System.exit(0);
}
try {
Connection dbConnection = DriverManager
.getConnection("jdbc:mysql://localhost/test?user=root&password=password");
System.out.println("Connection successful...");
Statement stmt = dbConnection.createStatement();
stmt.executeUpdate("create table Accounts ( name char(20) )");
} catch (SQLException e) {
System.out.println("database-ConnectionError: " + e);
System.exit(0);
}
}
Make sure you have added a proper mysql-connector to your build path. I used the: mysql-connector-java-5.1.24-bin.jar
static final String DB_URL = "jdbc:mysql://localhost:3306/sys";
Use database name in the URL.
It worked for me

Categories