public class Sample {
public static void main(String[] args) {
Connection con;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost/cluster", "root",
"password");
PreparedStatement pst = con
.prepareStatement("INSERT INTO EMPLOYEE_DETAILS (EMPLOYEE_ID,NAME,SALARY,DEPARTMENT,MANAGER)VALUES(?,?,?,?,?)");
pst.clearParameters();
pst.setObject(1, 101);
pst.setObject(2, "sam");
pst.setObject(3, 1000000);
pst.setObject(4, "IT");
pst.setObject(5, "jord");
pst.execute();
System.out.println("values got updted-----");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
for the first time this query is working fine and data is getting loaded into MySql data base.But when i execute the same programme after changing the values also the database is loading previously loaded values again and again..
why this is happening..
got it,the problem is actually with eclipse itself.After making any changes to the eclipse is not saving the new copy automatically and when we try to compile it is compiling the old copy without any new changes.If i manually save the code after any changes it is working fine...
Related
I have this code
public PreparedStatement InsertDepartmentQuery() {
try {
ps = conn.prepareStatement("INSERT INTO department (DepartmentNo,DepartmentName,DepartmentLocation) VALUES (?,?,?)");
}
catch(SQLException e) {
e.printStackTrace();
}
return ps;
}
and
public void InsertyTuple() {
int a = -1;
ps = InsertDepartmentQuery();
try {
ps.setInt(1, DeptNo);
ps.setString(2, DeptName);
ps.setString(3, DeptLocation);
a = ps.executeUpdate();
}
catch(SQLException e) {
e.printStackTrace();
}
System.out.println(a);
}
and
Department test = new Department(106, "TB_1", "Tabuk");
test.InsertyTuple();
It executes fine in Eclipse, even a select query in there returns the expected results. But none of the inserts are showing up in MySQL Workbench. I tried restarting the connection and it didn't work. Autocommits are on as when I tried to do a manual commit it told me so.
Wrong schema name
Well I found the problem so I'll just leave the answer and feel stupid later.
I had the connection started as
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=CONVERT_TO_NULL", username, password);
when it should've been
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/project?zeroDateTimeBehavior=CONVERT_TO_NULL", username, password);
the "project" replacing "mysql" is the name of my schema in MySQL.
I'm trying to connect my Java code to a db I've created in Google Cloud SQL, but I'm getting ClassNotFound and SQLException errors: -
java.lang.ClassNotFoundException: com.google.cloud.sql.mysql.SocketFactory
java.sql.SQLException: No suitable driver found for jdbc:mysql
I'm also getting a NullPointerException in code, in the getAllFilms() method at the line below, which I'm assuming is because the code isn't making a db connection: -
ResultSet rs1 = stmt.executeQuery(selectSQL);
Things I've done so far: -
Tested the Google Cloud SQL db credentials, through a client connection
Reviewed related posts, particularly [this one][1]
Been through the Google documentation
Added MySQL and Socket Factory Connector(j8) JARs to my project dependencies
Unfortunately I'm still unable to resolve. Hopefully someone can help. I've attached my Java code below. Thanks in advance...
Film oneFilm = null;
Connection googleSqlConnection = null;
Statement stmt = null;
String url = "jdbc:mysql:///<dbname>?<cloudSqlInstance>&socketFactory=com.google.cloud.sql.
mysql.SocketFactory&user=<user>&password=<pword>";
public FilmDAO() {
}
private void openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.google.cloud.sql.mysql.SocketFactory");
} catch (Exception e) {
System.out.println(e);
}
try {
googleSqlConnection = DriverManager.getConnection(url);
stmt = googleSqlConnection.createStatement();
} catch (SQLException se) {
System.out.println(se);
}
}
private void closeConnection() {
try {
googleSqlConnection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public ArrayList<Film> getAllFilms() {
ArrayList<Film> allFilms = new ArrayList<>();
openConnection();
try {
String selectSQL = "select * from films limit 50";
ResultSet rs1 = stmt.executeQuery(selectSQL);
while (rs1.next()) {
oneFilm = getNextFilm(rs1);
allFilms.add(oneFilm);
}
stmt.close();
closeConnection();
} catch (SQLException se) {
System.out.println(se);
}
return allFilms;
}
[1]: https://stackoverflow.com/questions/53693679/connecting-to-google-cloud-sql-with-java
Have you added the Cloud SQL JDBC SocketFactory and mysql-connector-java to your pom.xml?
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
I am using singleton database connection inside my java application, here is code of my connection manager class:
public abstract class DatabaseManager {
//Static instance of connection, only one will ever exist
private static Connection connection = null;
private static String dbName="SNfinal";
//Returns single instance of connection
public static Connection getConnection(){
//If instance has not been created yet, create it
if(DatabaseManager.connection == null){
initConnection();
}
return DatabaseManager.connection;
}
//Gets JDBC connection instance
private static void initConnection(){
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName="+dbName+";integratedSecurity=true";
DatabaseManager.connection =
DriverManager.getConnection(connectionUrl);
}
catch (ClassNotFoundException e){
System.out.println(e.getMessage());
System.exit(0);
}
catch (SQLException e){
System.out.println(e.getMessage());
System.exit(0);
}
catch (Exception e){
}
}
public static ResultSet executeQuery(String SQL, String dbName)
{
ResultSet rset = null ;
try {
Statement st = DatabaseManager.getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rset = st.executeQuery(SQL);
//st.close();
}
catch (SQLException e) {
System.out.println(e.getMessage());
System.exit(0);
}
return rset;
}
public static void executeUpdate(String SQL, String dbName)
{
try {
Statement st = DatabaseManager.getConnection().createStatement();
st.executeUpdate(SQL);
st.close();
}
catch (SQLException e) {
System.out.println(e.getMessage());
System.exit(0);
}
}
}
The problem is my code work perfect at the start but when time past it becomes really slow. What caused that problem and how can i fix that?
At starting time my application handles around 20 queries per second, after 1 hour of running it reaches to 10 queries per second and after 3 days of running it reaches to 1 query per 10 seconds!!
P.S: My application is a single user application that makes many queries through database.
P.S: Here is my JVM parameters in eclipse.ini:
--launcher.XXMaxPermSize
512M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
512m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms500m
-Xmx4G
-XX:MaxHeapSize=4500m
Unfortunately database is remote and I have not any monitoring access to it for finding out what is going on there.
Here is the example of my usage:
String count="select count(*) as counter from TSN";
ResultSet rscount=DatabaseManager.executeQuery(count, "SNfinal");
if(rscount.next()) {
numberofNodes=rscount.getInt("counter");
}
What caused that problem and how can i fix that?
The main problem that you have here is in the executeQuery() method.
You are not closing the Statement, I suppose that you have commented the line st.close() because you need the ResultSet open
for further processing.
I can see that your idea is to avoid see duplicate JDBC code in your application, but this is not the right approach.
The rule is: close the ResultSet and after that, close the Statement,
otherwise you are not releasing resources correctly and you expose to the kind of problem that you are describing.
Here you can find a good explanation about how to close resources correctly (take in mind that in your case you donĀ“t need
to close the connection)
Edit:
An example could be
try{
Statement st = DatabaseManager.getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet rsCount = st.executeQuery(count); //count="select count(*) as counter from TSN";
if(rsCount.next()) {
numberofNodes=rscount.getInt("counter");
}
} catch (SQLException e) {
//log exception
} finally {
rsCount.close();
st.close();
}
You should consider using a disconnected resultset like a CachedRowSet http://docs.oracle.com/javase/1.5.0/docs/api/javax/sql/rowset/CachedRowSet.html
public static ResultSet executeQuery(String SQL, String dbName)
{
CachedRowSetImpl crs = new CachedRowSetImpl();
ResultSet rset = null ;
Statement st = null;
try {
st = DatabaseManager.getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rset = st.executeQuery(SQL);
crs.populate(rset);
}
catch (SQLException e) {
System.out.println(e.getMessage());
System.exit(0);
}finally{
rset.close();
st.close();
}
return crs;
}
CachedRowSet implements ResultSet so it should behave like a ResultSet.
http://www.onjava.com/pub/a/onjava/2004/06/23/cachedrowset.html
In addition to these changes, I would recommend you use a pooled datasource to get connections and close them instead of holding on to one open connection.
http://brettwooldridge.github.io/HikariCP/
Or if you arent java7, bonecp or c3po.
EDIT:
To answer your question, this solves your problem because CachedRowSetImpl doesnt stay connected to the database while in use.
This allows you to close your Resultset and Statement after you've populated the CachedRowSetImpl.
Hope that answers your question.
Although Connection Manager would close Statement and Resultset automatically, but it would be better if you close them immediately.
There's nothing else in your code will effect your single thread task, so I bet there must be something wrong in your database. Try to find out if there's any database locking or wrong column index. And also have a look at database query status, find out where's the bottleneck.
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