Can't connect my SQL Server base to Java app on NetBeans - java

I have installed NetBeans IDE 12.3 on Lubuntu and SQL Server thanks to the microsoft documentation.
I have created my database using the command line tool sqlcmd (I don't have a GUI for sql server like you have on windows).
In the netbeans interface, I connected my sql server base to my java project, I see the base, I see the tables. Using the SQL tool of netbeans I can request them, add/delete entries etc. no problem.
But I would like to make request in the java code itself, not in the sql tool of netbeans. The documentation says I should create a Connection object, but can't I just use the connection I created through the graphical netbeans interface ?
I get this error: java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost\db:1433;databaseName=ConservatoireDB
Here is the code in main:
ResultSet resultSet = null;
try (Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost\\db:1433;databaseName=ConservatoireDB");
Statement statement = connection.createStatement();) {
// Create and execute a SELECT SQL statement.
String selectSql = "select * from salle";
resultSet = statement.executeQuery(selectSql);
// Print results from select statement
while (resultSet.next()) {
System.out.println(resultSet.getString(2) + " " + resultSet.getString(3));
}
}
catch (SQLException e) {
e.printStackTrace();
}
By the way, my project is a graphical app using Swing library.

Related

Difficulty starting the database in Netbeans using DB Derby and DBeaver

I am trying to make a DB Derby database in Netbeans called eportdatabase, and connect it to DBeaver. However, I am having trouble starting the database at all.
try
{
String databaseURL = "jdbc:derby:eportdatabase;create=true";
Connection con = DriverManager.getConnection(databaseURL);
Statement st = con.createStatement();
if (!doesTableExists("Accounts", con))
{
String sql = "CREATE TABLE Accounts (Username varchar(250), Password varchar(250)) ";
st.execute(sql);
System.out.println("Table Does Not Yet Exist!");
}
else if(doesTableExists("Accounts", con)) {
System.out.println("Table Already Exists!");
}
con.close();
}
catch (Exception e)
{
System.out.println(e);
}
However, it does not work. When I run the application, this IOException Error Comes Up:
java.sql.SQLException: Failed to start database 'eportdatabase' with class loader jdk.internal.loader.ClassLoaders$AppClassLoader#45ee12a7, see the next exception for details.
Is there something evidently wrong with my code? Or do I need to update my drivers (which I am having trouble doing)?
UPDATE: Thanks to help with printing errors from comments, I figured out the issue; I still had the old database folder in my application folder, which was present from before I updated to JDK 15, hence not being compatible with Netbeans' software. many thanks!

Error or wrong type of code while creating connection & execute SQL query statements using mysql in java

I'm using MySQL 5.7 with Java in Eclipse, and the connection statement below code below is causing an error when I try to connect:
try
{
//1. Get a connection to database
jdbc:mysql://localhost:3306/databaseName?autoReconnect=true;useSSL=false;
// 2. Create a statement
Statement myStmt=myConn.createStatement();
// 3. Execute SQL query
ResultSet myRs=myStmt.executeQuery("select * from employee");
//4. Process the result set
while(myRs.next())
{
System.out.println(myRs.getString("last_name")+","+myRs.getString("first_name"));
}
}
catch(Exception exc){
exc.printStackTrace();
}
First things first.
Code will only be used to validate the error. So you must paste the error fired by your program.
Since we don't have enough information to the problem, I will just cover basic troubleshooting.
Basic trouble shooting:
Do you have the driver? if not, you can download it here.
Next, Do you have the driver on your project class path? If not yet, you must add it. see how here
Did you load the driver to the program? if not, Class.forName("com.mysql.jdbc.Driver"); // Load Driver like that before doing anything.
Did you establish the connection? if not, Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/DATABASE","USERNAME","PASSWORD");//3306 or port number depends on you config, same with DATABASE, USERNAME, PASSWORD
After the connection were established, so you should create a statement object like Statement s = con.createStatement(); // Create Statement. This will be used to execute sql commands.
finally, you can execute the commands like s.execute("select * from employee"); // Execute Query NOTE that s here is the variable created on number 5.
If all of the above were properly done but still gets an error, check if your have the database server running. In you case, mysql. Make sure there were not other installation of mysql prior to your current mysql. Sometimes, it will mess up your database. Troubleshooting your mysql, see mysql official doc here
While possible error is the datatype of mysql to your java code or getting a column that does not exist on your query or worse the column does not exist on your table.
Hope that help you and other who needs it.

Creating Table in AWS Redshift with AWS Java SDK

I am trying to create a temporary table inside of AWS redshift using the java SDK.
// Redshift JDBC 4.1 driver: com.amazon.redshift.jdbc41.Driver
String command = "CREATE TABLE test (FirstName varchar(255));"
Class.forName("com.amazon.redshift.jdbc41.Driver");
conn = DriverManager.getConnection(dbURL, props);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(command);
When running this code the table is created successfully but on the return, an error is thrown
com.amazon.dsi.dataengine.impl.DSISimpleRowCountResult cannot be cast to com.amazon.dsi.dataengine.interfaces.IResultSet
Everything will work if I use a command that returns something, such as
"Select * FROM test;"
"SELECT * FROM test LIMIT 0;"
I didn't see any documentation for this problem in the AWS READMEs or other stack overflow questions for this problem. It seems to me that there is a special class in the driver for when nothing is returned from the statement that is not able to be cast to the ResultSet class.
The redshift driver version is 1.1.13.1013 .
Any help would be greatly appreciated!
I had the same problem. You can solve this easily. Instead of
stmt.executeQuery(command);
please try
stmt.execute(command);

Oracle - Available data not visible in SQL Command Line/Java Program

I am creating a basic java application with Oracle database. I use Oracle SQL Developer to interact with oracle database.
I created tables and inserted data using Oracle SQL Developer and all operations were successful.But when I try to get those records in the java program, it does not get any results.
I debugged the java program and found out the issue is the resultset not getting any records from DB.(Other things are fine)
try {
stmt = dbConnector().createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString("AGE"));
}
} catch (SQLException e) {
e.printStackTrace();
Because of that, I tried to verify using SQL command line and it did not show the entries I entered using SQL developer. I cannot figure out what is wrong. Please refer the attached.
A help regarding this is much appreciated.
Please make sure that you have commit the transactions done in Oracle SQL Developer. Most probably that may be the reason for not showing records both in SQL plus & your java program.
You may commit by clicking on the commit button on Oracle SQL Developer toolbar (i.e. 6th button from left)

different results from query in java code and on oracle db server: but no connection error

I have java code that connects to a remote oracle 11g EE db server. If i run a particular query in sqlplus it returns one result
SQL> SELECT COURSENAME from COURSES where skillID=1;
COURSENAME
--------------------
basic
But if I run the same query from the java code below it returns no results. I can copy the query syntax out of the query variable in the java debugger and running it on oracle so I know there is no syntax issue with the query. Also, it is not SQL exceptions or class not found exceptions so it seems to be running the query successfully -- just returning zero results.
What might be going on?
private String getCourseForSkill(int skillID){
try{
Class.forName("oracle.jdbc.OracleDriver");
String query="SELECT COURSENAME from COURSES where skillID=" + skillID ;
con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement();
rs = stmt.executeQuery(query);
rs.next();
return rs.getString("COURSENAME");
}
catch (ClassNotFoundException ex){
System.out.println(ex.getMessage());
}
catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return null;
}
I think you're connecting to different Oracle instances, or more likely, as different Oracle users in the two cases
#GreyBeardedGeek the URL looks like "jdbc:oracle:thin:#website:port:orcl I get to the manual query by doing ssh#website, authenticating and then running command=sqlplus
Safer to run sqlplus <username>/<password>#<orainstancename>, because you can explicitly specify the oracle instance ID. In your case, it seems your program is using jdbc connection jdbc:oracle:thin:#website:port:orcl, so your orainstancename would be 'orcl' - just ensure that your tnsnames.ora file has the instance 'orcl' with the same 'port' as used by the jdbc connection
How to debug a little more
Run the following code:
con = DriverManager.getConnection(url, user, password);
con.setAutoCommit(false);
String insert="INSERT INTO COURSES (SKILLID, COURSE)"+ // can add other columns
"values (?, ?) );" // add ? for other columns
PreparedStatement ps = con.createPreparedStatement();
ps.setInt(1, 999);
ps.setString(2, "Complete Bullwarks");
// can set other columns
ps.executeUpdate(insert);
con.commit();
NOW connect manually, re-run your original select statement & see if the added row is there. If no error in java and no new row in Oracle: extremely likely you're using 2 different Oracle instances/schemas.
ALSO rerun your original java select code, but with SkillID=999 - extremely likely it will work.
Cheers
I had to do a commit to add the rows. When I typed commit; into the sql plus terminal then the remote jdbc connection could 'see' the rows. I am used to SQL server where you don't have to explicitly do these kinds of commits when using linq-to-sql or sql management studio.
It can be three issues.
1) skillID <> 1 in your Java code. Add debug and check.
2a) You are connecting to another database.
2b) You are connecting to the same database but SELECTING from a table in another schema.
To check 2a and 2b:
select user from dual; -- connect username
select name from v$database; -- database name
select host_name from v$instance; -- host name database is running on
This query returns all three into one result.
select user || '' || d.name || '' || i.host_name
from v$database d, v$instance i;
Assuming you are actually connecting to the same database this is caused by not committing the INSERT in the sql*plus connection.
Oracle by default does not run in auto-commit mode when connecting via OCI (which sql*plus uses to connect). Any DML(INSERT ...) executed in sql*plus will not be visible to any other session until it is committed. This is because Oracle provides a read committed isolation level by default. The only thing visible to other users across sessions are write locks.
It doesn't matter if you connect the second connection via JDBC or OCI, it won't see the changes till you commit the first connection.
To test this out try opening 2 sql*plus connections and run the following:
-- Executing DDL in Oracle causes an implicit commit before and after the
-- command so the second connection will see the existence of this table:
CREATE TABLE foobar ( x VARCHAR(1) );
Execute this in connection #1 - you should get zero (we haven't inserted anything yet):
SELECT COUNT(*) FROM foobar;
Execute this in connection #2:
INSERT INTO foobar ( x ) VALUES ( 'A' );
Execute this in connection #1 - you should still get zero (INSERT is not committed so connection #1 cannot see it):
SELECT COUNT(*) FROM foobar;
Execute this in connection #2:
COMMIT;
Execute this in connection #1 - you should get 1 (it's committed now):
SELECT COUNT(*) FROM foobar;

Categories

Resources