Not able to execute the Create table sql query through java - java

I am trying to create the table through java string but it is displaying error as table doesn't exist but when I run the same query directly on workbench it runs fine. Below is my code
String url = "jdbc:mysql://localhost:3306/" ;
String dbname = "tweetmap";
String username = "root";
String password = "root";
try
{
// SQL Driver needed for connecting to Database
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection(url+dbname,username,password);
c.setAutoCommit(true);
stmt = c.createStatement();
//Creating the Database if not Already Present
String sql = "CREATE TABLE if not exists senti "
+ "( latitude double NULL, "
+ "longitude double NULL, "
+ "Sentiment TEXT NULL) ";
stmt.executeUpdate(sql);
if(sentiment != null){
stmt1 = c.createStatement();
stmt1.executeUpdate("INSERT INTO `senti`(latitude,longitude,Sentiment) VALUE ('"+lati+"','"+longi+"','"+sentiment+"')");
}
}
catch(Exception e){
e.printStackTrace();
}

this is the problem stmt.executeUpdate(sql);
instead of executeUpdate use execute(String SQL) method.
execute(String SQL) is used for DDL/DML statement
while executeUpdate(String SQL) is used only for DML operation

Best way to execute any query in JDBC is using execute() method. This method can be used for any kind of query.
I hope below link will help you to understand more.
http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#execute(java.lang.String)

Related

multiple sql command

I'm trying to execute multiple sql commands, but it gives me "error in your SQL syntax;"
Db_Connection dbconn = new Db_Connection();
Connection myconnection = dbconn.Connection();
String sqlString = "SELECT DISTINCT std_id FROM std_crs WHERE crs_id ='222123'; "
+ "SELECT * FROM cplus_grades ;";
Statement myStatement = myconnection.createStatement();
boolean results = myStatement.execute(sqlString);
do {
if (results) {
ResultSet rs = myStatement.getResultSet();
while (rs.next()) {
}
rs.close();
}
results = myStatement.getMoreResults();
} while(results);
myStatement.close();
I did a small test with three JDBC drivers:
MS SQL: works, returns two result sets
MySQL: fails with a syntax error - that is what you are seeing
HSQLDB: runs, but returns only one result set.
So I guess it simply depends on the JDBC driver if this technique works. Maybe it works only in MS SQL JDBC.
UPDATE:
It also works with Postgres.
please
1. String dbUrl = "jdbc:mysql://yourDatabase?allowMultiQueries=true";
this should be your jdbc connection url

Incorrect output of database program

I am doing practice for JDBC and using NetBeans 8.1. I created a table in MS Access and wrote a program. But the problem is that when I pass column index then my program runs successfully. But I pass column name as in my table in MS Access then there occurs an error that
Column not found
I am pasting code of my program and try to explain my problem further.
package database;
import java.sql.*;
public class Database {
public static void main(String[] args) {
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:personDSN";
Connection con = DriverManager.getConnection(url);
Statement st = con.createStatement();
String sql = "SELECT *FROM students";
ResultSet rs = st.executeQuery(sql);
while(rs.next())
{
String Name = rs.getString(2);
String add = rs.getString(3);
String pNum = rs.getString(4);
System.out.println(Name + " " + add + " " + pNum);
}
con.close();
}
catch(ClassNotFoundException | SQLException sqlEx)
{
System.out.println(sqlEx);
}
}
}
As you can see in while loop that i have passed column index in getString() function. In this case my program runs successfully. But when i pass name of field/attribute which is in my database table, then it gives me error that "Column not found". For example if I pass getString("name") then it gives me above error.
Please help me to solve my problem.
Note: I have checked again and again that there is no spelling mistake in my parameter opposite to actual table in ms access.

postgres how to get data from multiple databases

i have 2 PostgreSQL databases on different port: DB1 on port 5432 and DB2 on port 5431
and i have code to get data from DB1 like this :
try {
Class.forName("org.postgresql.Driver");
String conString = "jdbc:postgresql://127.0.0.1:5432/DB1?user=MyUser&pass=MyPass" ;
c = DriverManager.getConnection(conString);
st = c.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()){
vaArrL.add(rs.getDouble("va"));
vbArrL.add(rs.getDouble("vb"));
vcArrL.add(rs.getDouble("vc"));
}
and work good when i send singe query to DB1 only.
but now, i have query to both databases together like :
select va, vb from DB1.public.t1 where datatime >= 1417384860 and datatime <= 1417381199
union
select va, vb from dblink('hostaddr=127.0.0.1 port=5431 dbname=DB2 user=MyUser password =MyPass '::text,
'select va, vb
from Db2.public.t2 order by datatime ')
datos(va integer,vb integer);
when i run query from pgAdmin i get result
but when i sent query to gunction i get : connection not available
Now. How can i send my query to function and i get values?
Can you try using JDBC's setCatalog method?
setCatalog's javadoc states that:
Calling setCatalog has no effect on previously created or prepared
Statement objects. It is implementation defined whether a DBMS prepare
operation takes place immediately when the Connection method
prepareStatement or prepareCall is invoked. For maximum portability,
setCatalog should be called before a Statement is created or prepared.
try {
Class.forName("org.postgresql.Driver");
// Connect to DB1 (specified in connection string/URL).
String conString = "jdbc:postgresql://127.0.0.1:5432/DB1?user=MyUser&pass=MyPass" ;
c = DriverManager.getConnection(conString);
st = c.createStatement();
// Execute query on DB1.
ResultSet rs = st.executeQuery(query);
while (rs.next()){
vaArrL.add(rs.getDouble("va"));
vbArrL.add(rs.getDouble("vb"));
vcArrL.add(rs.getDouble("vc"));
}
// Switch to DB2 and execute query.
c.setCatalog("DB2");
Statement st2 = c.createStatement();
ResultSet rs2 = st2.executeQuery(...);
}
If the JDBC driver doesn't support setCatalog, then you can execute the SQL query USE DB2 explicitly but this might affect already open statements (I'm not sure about this).
Edit: OP wants all results from both databases in the same ResultSet.
Assuming that DB1 and DB2 are on same server, I'd recommend creating a view in database DB1 which can access tables in database DB2 and return combined results. Then you can just SELECT * from the view via JDBC and get the results.
You can use a query like this for your view (assuming that the view is created in DB1):
SELECT all.va, all.vb FROM
(SELECT va, vb, datatime FROM t2
UNION
SELECT va, vb, datatime FROM DB2.public.t2) all
ORDER BY all.datatime
Note: To access a table in another database, you need to specify [db-name].[schema].[tablename].
If your query needs dynamic arguments, then you can create a stored procedure instead of a view.
i am find 1 solution
i am use 2 connection and send to query from client to xmlrpc server, here :
String conString = "jdbc:postgresql://" + host + ":" + port + "/" + DBName +
"?user=" + user + "&pass=" + pass;
String conString1 = "jdbc:postgresql://" + host + ":" + port2 + "/" + DBName2 +
"?user=" + user + "&pass=" + pass;
c = DriverManager.getConnection(conString);
c2 = DriverManager.getConnection(conString1);
st = c.createStatement();
st2 = c2.createStatement();
List<ResultSet> resultSets = new ArrayList<>();
resultSets.add(st.executeQuery(query));
resultSets.add(st2.executeQuery(query2));
ResultSets rs = new ResultSets(resultSets);
while (rs.next()){
unbArrL.add(rs.getUnbalance("unbalance"));
}
and resultSets class to get values from DB is :
class ResultSets {
private java.util.List<java.sql.ResultSet> resultSets;
private java.sql.ResultSet current;
public ResultSets(java.util.List<java.sql.ResultSet> resultSets) {
this.resultSets = new java.util.ArrayList<>(resultSets);
current = resultSets.remove(0);
}
public boolean next() throws SQLException {
if (current.next()) {
return true;
}else if (!resultSets.isEmpty()) {
current = resultSets.remove(0);
return next();
}
return false;
}
public Double getUnbalance(String unbalance) throws SQLException{
return current.getDouble("unbalance");
}
}

Delete selected row in database

Why is this not working for me? I keep getting the error:
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
My code:
private void speler_deleteActionPerformed(java.awt.event.ActionEvent evt) {
int row = tbl_spelers.getSelectedRow();
int SpelerID = (int) tbl_spelers.getValueAt(row, 0);
Speler speler = new Speler();
try {
DBClass databaseClass = new DBClass();
Connection connectie = databaseClass.getConnection();
// NOG ONVEILIG - WACHTEN OP DB SELECT IN DBCLASS!!!
String deleteQry = "DELETE FROM `Speler` WHERE SpelerID = " + SpelerID + ";";
ResultSet rs = databaseClass.GetFromDB(deleteQry);
} catch (SQLException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
You have to use excuteUpdate() for delete.
Docs of excuteUpdate()
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.
Where as executeQuery()
Executes the given SQL statement, which returns a single ResultSet object.
Firstly, you need to use excuteUpdate() for the delete, and next
String deleteQry = "DELETE FROM `Speler` WHERE SpelerID = " + SpelerID + ";";
remove the semi-colon and the "`" which encloses the table name "Speler", from the query.
You need to execute you query using executeUpdate()
Also, you just need to make a slight adjustment to your String deleteQry as follows:
String deleteQry = "DELETE FROM Speler WHERE SpelerID = " + SpelerID;
Hope this helps...
executeQuery() method of jdbc is to select records, you can use executeUpdate() for update operations. Please refer to the documentation for the purpose/ intent of each method:
boolean execute()
Executes the SQL statement in this PreparedStatement object, which may
be any kind of SQL statement.
ResultSet executeQuery()
Executes the SQL query in this PreparedStatement object and returns
the ResultSet object generated by the query.
int executeUpdate()
Executes the SQL statement in this PreparedStatement object, which
must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement
that returns nothing, such as a DDL statement.

How to change the database name and table using java?

i try to understand this part of code:
Properties details= new Properties();
details.load(new FileInputStream("details.properties"));
String userName = details.getProperty("root");
String password = details.getProperty("mysqlpassword");
String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
PreparedStatement st = conn.prepareStatement("insert into 'Email_list' values(?)");
for(String mail:mails)
i understand that test database is a default database. but if i want to use an existing database, i will just modify test to another database name isn't it?
If yes how do i modify my code if my new database is Test2 with table name Email which contains mail column with varchar(100)
i try to replace test by Test2 Email_list by Email but i don't know where to put the column name mail.
Thank you for help
The INSERT statement you use omits the columns.
INSERT INTO tablename VALUES (1, 2, 3)
can be written if the table has three columns and for all three columns values are provided.
If some columns can be left empty or have default values, you can write
INSERT INTO tablename (column1, column2) VALUES (1, 2)
In this cas the value for column3 is null or the default value.
So in your case the column name is put nowhere.
You are missing PORT number in your connection string...
String url = "jdbc:mysql://localhost/test"; should be String url = "jdbc:mysql://localhost:PORT_NUMBER/test"; like String url = "jdbc:mysql://localhost:3306/test";
Let me know if you have any queries...
Also, Check below how Prepared Statement works
import java.sql.*;
public class TwicePreparedStatement{
public static void main(String[] args) {
System.out.println("Twice use prepared statement example!\n");
Connection con = null;
PreparedStatement prest;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:
//localhost:3306/jdbctutorial","root","root");
try{
String sql = "SELECT * FROM movies WHERE year_made = ?";
prest = con.prepareStatement(sql);
prest.setInt(1,2002);
ResultSet rs1 = prest.executeQuery();
System.out.println("List of movies that made in year 2002");
while (rs1.next()){
String mov_name = rs1.getString(1);
int mad_year = rs1.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
prest.setInt(1,2003);
ResultSet rs2 = prest.executeQuery();
System.out.println("List of movies that made in year 2003");
while (rs2.next()){
String mov_name = rs2.getString(1);
int mad_year = rs2.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Good Luck!!!

Categories

Resources