Issue in connecting MS SQL server using Java program - java

I am having a problem in executing a simple select statement in Microsoft Sql Server DB using a Java program. I am facing below 2 issues,
Code by using statement * Resultset - program just hungs near the executequery() method and no progress after that.
Sample code:-(Full code pasted below)
Statement sta = conn.createStatement();
String Sql3 = "select name from dbo.network";
sta.executeQuery(Sql3);
ResultSet rs=sta.getResultSet();
code with preparestatment * Resultset throws error saying
The method executeQuery() cannot take arguments on a PreparedStatement or CallableStatement
Sample Code:-
PreparedStatement ps = conn.prepareStatement(Sql3);
ResultSet rs = ps.executeQuery(Sql3);
Complete Code:-
public class DbConnectionTest {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
System.out.println("Entered into main method");
String userName ="***";
String password ="***";
String url ="jdbc:sqlserver://****:1433;databaseName=***";
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);
System.out.println("test");
Statement sta = conn.createStatement();
String Sql3 = "select name from dbo.network";
//PreparedStatement ps = conn.prepareStatement(Sql3);
//ResultSet rs = ps.executeQuery(Sql3);
sta.executeQuery(Sql3);
//sta.getMoreResults();
//sta.getMoreResults();
ResultSet rs=sta.getResultSet();
if(rs != null)
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}catch(Exception se){
//Handle errors for JDBC
se.printStackTrace();
}
}
}
In Addition, I confirm the below,
Same query executes fine in the database.
SQL Browser Server service is running fine
TCP/IP is enabled
Credentials and the URL string are correct
sqljdbc4.jar is used.
Please help me with this issue.

Related

Java Prepared Statement syntax to connect hive server for describing table

trying to establish connection to hive and describe a table.
enter code here
String queryTable= "dummydb.dummy_table";
String driverName = "org.apache.hive.jdbc.HiveDriver";
try {
Class.forName(driverName);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
//connect hive server (no issue in that)
String hiveUrl = PropertyLoader.getInstance("staging").getDruidHive();
Connection con = DriverManager.getConnection(hiveUrl, "hadoop", "");
##Working code is below:
String sql = "describe formatted dummydb.dummy_table" ;
PreparedStatement pstmt = con.prepareStatement(sql);
ResultSet rs1 = pstmt.executeQuery();
##But I try to use this which is not working:
String queryTable="dummydb.dummy_table"
String sql1 = "describe formatted ?" ;
PreparedStatement pstmt = con.prepareStatement(sql1);
pstmt.setString(1, queryTable);
ResultSet rs1 = pstmt.executeQuery();
Error
org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: ParseException line 1:19 cannot recognize input near 'formatted' ''dummydb.dummy_table'' '' in describe statement

How to use placeholder inside sql replace() in java?

I want to use placeholder inside sql replace function in java.
Following is the code.
import java.sql.*;
public class TestDB {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("class");
Connection con = DriverManager.getConnection("url","username","password");
PreparedStatement ps = null;
String query = "select name from image where id >= replace(?,'','','''') and id <= replace(?,'','','''') and name like ''%aa'' order by id;";
ps= con.prepareStatement(query);
ps.setString(1, "1");
ps.setString(2, "10");
ResultSet rs = null;
rs= ps.executeQuery();
while(rs.next())
{
System.out.println(rs.getString(1));
}
}
}
In ps= con.prepareStatement(query); line I am getting:
Exception in thread "main" java.sql.SQLException: An illegal character has been found in the statement.
Actually using a simple create statement it works fine. But when I use preparedstatement with placeholder it's throwing exception.
Can anyone let me know what the issue is?

how to insert bulk data from one database to another data base same structure using java

I have two SQL server running on two different location having same structure but different IP a = 100.0.0.1 and IP b = 192.0.0.1. I have a table a.table and b.table of same structure. Now i want to move all data that is in a. Table from 100.0.0.1 machine to b.table machine 192.0.0.1 .I want to transfer this data using java either connection or by hibernate. Currently i am doing this manually by running SQL query.
Here is the code you can use
import java.sql.*;
import java.io.*;
import java.util.*;
public class test1
{
public static void main(String[] argv) throws Exception
{
try
{
Connection con = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/old","user","pass");
Connection con1 = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/new","user","pass");
String sql = "INSERT INTO users("+ "name,"+ "active,"+ "login,"+ "password)"+ "VALUES(?,?,?,?)";
Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
PreparedStatement pstmt = con1.prepareStatement(sql);
ResultSet rs = statement.executeQuery("SELECT * FROM users");
while ( rs.next() )
{
String nm = rs.getString(2);
Boolean ac = rs.getBoolean(3);
String log = rs.getString(4);
String pass = rs.getString(5);
pstmt.setString(1, nm);
pstmt.setBoolean(2, ac);
pstmt.setString(3, log);
pstmt.setString(4, pass);
pstmt.executeUpdate();
}
con.close();
con1.close();
}
catch (SQLException e)
{
System.out.println("could not get JDBC connection: " +e);
}
}
}
Create a connection with something like this
Connection con=DriverManager.getConnection(url, dbProperties);
//then create a query
String query = "select * from a.table";
Statement statement = connect.createStatement(query);
save result in resultset or somewhere else : ResultSet rs = statement.executeQuery(); then create a second connection to your other database like above and call an insert for each result in your resultset. there might be much better methods to insert so much data. i hear about bulk operations but i don't know how they work

connecting a website to its database

I'm creating a website for the first time all by myself. I'm doing the logic in Java (I use Ubuntu), and I have written the SQL script for the data base on windows using pgAdmin3 (postgresql).
How do I connect my java program to its database?
If its just java and mysql, then you can try something like this
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/databaseName", "username","password");
As in the example below
public boolean isIdInDb(String id) throws SQLException{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/databaseName", "username","password");
String rawInfoDb = "select user_id from users ";
Statement statement = conn.createStatement();
ResultSet rSet = statement.executeQuery(rawInfoDb);
boolean isIt = false;
while(rSet.next()){
if(id.equals(rSet.getString(1))){
isIt = true;
}
}
return isIt;
}

I have created a search bar in java. But it has some errors

try {
con = DriverManager.getConnection(url, username, password);
String qry = "SELECT * FOME users WHERE id=?";
pst = con.prepareStatement(qry);
pst.setString(1, txtSearch.getText());
rs = pst.executeQuery();
tblEmployee.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
e.printStackTrace(); //Show what is the catched error
}
rs = pst.executeQuery(); doesn't work and throws following error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near 'FOME users
WHERE id='df'' at line 1
You should have believed the error. FOME should be FROM,
String qry = "SELECT * FROM users WHERE id=?";
There is a type in SQL statement. It should be
String qry = "SELECT * FROM users WHERE id=?";
Notice the typo, FOME.
Whenever you get exceptions like these, first execute the query using SQL client before doing it through Java.

Categories