Set Default Database name for queries in TERADATA - java

I have this query:
Connection conn = null;
stmt = conn.createStatement();
stmt.execute("SELECT * FROM school.users");
and I got results from that query. If I try to implement this following code in java to set a default database:
stmt.execute("database school");
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
I have this error:
Exception-> [Teradata Database] [TeraJDBC 14.10.00.17] [Error 3807] [SQLState 42S02] Object 'users' does not exist
Can You see what is Wrong?

Add DATABASE param in the url and try.
eg. url="jdbc:teradata://exampleDns/DATABASE=school"
I hope this is what you are looking for

Try this:
Connection conn = null;
Statement stmt = null;
try{
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
}
catch(SQLException se){
se.printStackTrace();
finally{
stmt.close();
conn.close();
}

What if you use the executeUpdate "method" of the Statement?
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
stmt.executeUpdate("database school");
ResultSet rs = stmt.executeQuery("SELECT * FROM users");

Related

java oracle jdbc resultset empty but record is available in the table

I'm running java 1.8 connecting to oracle 12c using ojdbc7.jar for jdbc connection.
This is the code that execute to retrieve the data
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#" +
ipAddress + ":1521:" + dbname,userName,password);
Statement stmt=con.createStatement();
String query = "select * from table_name";
ResultSet rs = stmt.getResultSet();
while (rs.next()) {
System.out.println(rs.getString(1));
}
but the code is not entering the while loop.
When i try exeuction the same query in DB, I could see the table has 10 entries.
Does anyone know what could be the reason?
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#" +
ipAddress + ":1521:" + dbname,userName,password);
Statement stmt = con.createStatement();
String query = "select * from table_name";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException e ) {
} finally {
if (stmt != null) { stmt.close(); }
}

Exception in prepared statement

Following is the code.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:cse");
//Statement stmt;
ResultSet rset;
//stmt = conn.createStatement();
String sql = " Select * from registration where id=?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, "101");
rset = pst.executeQuery(sql);
while (rset.next()) {
arr.add(rset.getInt("id"));
arr.add(rset.getString("first"));
arr.add(rset.getString("last"));
arr.add(rset.getInt("age"));
}
System.out.println(arr);
pst.close();
conn.close();
For the above am getting "Error: java.sql.SQLException: Driver does not support this function". What might be the problem?
You are misusing the PreparedStatement interface. When using PreparedStatements, you should prepare the statement with your query, bind all necessary parameters and then execute it without any SQL - this will cause the statement to execute the previously prepared SQL statement:
String sql = "Select * from registration where id=?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, "101");
rset = pst.executeQuery(); // Note - No args in the executeQuery call

Get next ResultSet in JDBC

I have 2 queries and therefore 2 ResultSet's returned from MySQL in Java through createStatement(). The queries are like
SELECT * FROM abc;
SELECT * FROM def;
These queries are run simultaneously in single createStatement() like
CreateConnection();
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("select * from ABC; select * from DEF;");
while(rs.next()) {
//Iterate through first resultset
}
rs.close();
stat.close();
conn.close();
How can I get the next ResultSet returned by second query?
Use Statement#getMoreResults and Statement#getResultSet methods:
ResultSet rs = stat.executeQuery("select * from ABC; select * from DEF;");
while(rs.next()) {
//Iterate through first resultset
}
rs.close();
if (stat.getMoreResults()) {
rs = stat.getResultSet();
while(rs.next()) {
//Iterate through second resultset
}
}
stat.close();
In order that make this method to work, you should add allowMultiQueries=true property to your connection by appending this property to your connection url:
String url = "jdbc:mysql://yourServer:yourPort/yourDatabase?allowMultiQueries=true";
Note that you can perform multiple queries per Statement using a single Connection object:
Connection con = ...
List<String> sqlStatements = ... //a list with all the SELECT statements you have
for (String query : sqlStatements) {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
//do your logic here...
}
rs.close();
stmt.close();
}
conn.close();

JDBC MySql bind variable syntax error in where clause

I am getting this error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
public static Person getDetails(int id) {
Connection conn = null;
PreparedStatement stmt = null;
Person newPerson = new Person();
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
String sql = "SELECT firstName, lastName, birthday FROM person WHERE id=?";
System.out.println("SQL Statement:\n\t" + stmt);
stmt = conn.prepareStatement(sql);
System.out.println("Prepared Statement before bind variables set:\n\t" + stmt.toString());
//Bind values into the parameters.
System.out.println("ID " + id);
stmt.setInt(1, id); // This would set id
System.out.println("Prepared Statement after bind variables set:\n\t" + stmt.toString());
// Let us select all the records and display them.
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
Date birthday = rs.getDate("birthday");
newPerson.setBirthday(birthday);
newPerson.setFirstName(firstName);
newPerson.setLastName(lastName);
newPerson.setId(id);
//Display values
System.out.print("ID: " + id);
System.out.print(", First: " + firstName);
System.out.println(", Last: " + lastName);
System.out.println(", Birthday: " + birthday);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
return newPerson;
}
I have success executing the query without the where clause. I have looked at many examples and nothing I try fixes this.
Don't use executeQuery(String) with prepared statements...
Instead of....
ResultSet rs = stmt.executeQuery(sql);
use...
ResultSet rs = stmt.executeQuery();
Take a look at How to use Prepared Statements for more details
If I understand your question, the problem is you used Statement.executeQuery(String). I'm fairly certain you meant to use PreparedStatement.executeQuery(),
// Let us select all the records and display them.
ResultSet rs = stmt.executeQuery(sql); // <-- adding sql here makes it use the
// Statement version.
You wanted to use
// Let us select all the records and display them.
ResultSet rs = stmt.executeQuery(); // <-- use the version from PreparedStatement
Change
ResultSet rs = stmt.executeQuery(sql);
to
ResultSet rs = stmt.executeQuery();

Retrieving a specific value from mysql database based on parameters

I want to retrieve a users name from the username and password that they have entered into textfields. i want to pass these values as parameter to method which will then identify the users name for printout. please help. something like this...
public void getUser(String username, String password)throws SQLException{
String qry = "SELECT UserName From USER....";
Connection con = null;
PreparedStatement stmt = null;
try{
con = DriverManager.getConnection("URL");
stmt = con.prepareStatement(qry);
stmt.executeUpdate();
If not is an update or an insert, don't use executeUpdate()
You must use executeQuery().
Try this:
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String qry = "SELECT UserName From USER where username=? and password=?";
try{
con = DriverManager.getConnection("URL");
stmt = con.prepareStatement(qry);
stmt.setString(1, username);
stmt.setString(2, password);
rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("UserName"));
}
...
Regards
Assuming that you want to get the user's full name from db and your table structure is something like this:
fullname | username | password
you could do the following:
Connection c = null;
PreparedStatement s = null;
try {
c = DriverManager.getConnection("URL");
s = c.prepareStatement("SELECT fullname FROM user WHERE username=? and password=?");
s.setString(1, username);
s.setString(2, password);
ResultSet rs = s.executeQuery();
if(rs.next())
return rs.getString("fullname");
return null; // no user found!
} catch(SQLException e) {
System.err.println(e.getMessage());
} finally {
// close s and c
}
Note: This assumes that the password that is passed to the method is in the same "form" as it is stored in db (i.e. either plain text or hashed (+salted))
try this its very simple example
private boolean validate_login(String id,String password) {
try{
Class.forName("org.sqlite.JDBC"); // MySQL database connection
Connection conn = DriverManager.getConnection("jdbc:sqlite:studentdb.sqlite");
PreparedStatement pst = conn.prepareStatement("Select * from student_table where id=? and password=?");
pst.setString(1, id);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if(rs.next())
return true;
else
return false;
try{
Class.forName("org.sqlite.JDBC"); // MySQL database connection
Connection conn = DriverManager.getConnection("jdbc:sqlite:studentdb.sqlite");
PreparedStatement pst = conn.prepareStatement("Select * from student_table where id=? and password=?");
pst.setString(1, id);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if(rs.next())
return true;
else
return false;
}
catch(Exception e){
e.printStackTrace();
return false;
}
}

Categories