I've read about inheritance or using the import. I just simply am unable to get the right answer. Firstly my code is of the following form:
class queries{
String query1="Select * from "+tableName+";
String query2="Select "+columnName+" from "+tableName+";
}
Now, I have another class where I wish to make make SQL queries using the queries mentioned in the queries class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
class test{
public static void main(String args[])throws SQLException
{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("This is Wrong");
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection connect = DriverManager
.getConnection("SQLCONNECTION");
PreparedStatement preparedStatement = connect
.prepareStatement(THIS SHOULD CALL query1 or query2);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.println("THIS RUNS");
//display text
}
preparedStatement.close();
connect.close();
}
}
So well, I need to figure out how to call query1 or query2 from the queries class in test. Sorry, but I hope someone can help me how to do this in a clean way. I can also create a Hashtable in queries where I call the respective query based on its name.
Thanks a lot.
class queries
{
public static String getQuery1(String tableName)
{
return "Select * from "+tableName;
}
public static String getQuery2(String tableName, String columnName)
{
return "Select "+columnName+" from "+tableName;
}
}
Then do this:
PreparedStatement preparedStatement =
connect.prepareStatement(queries.getQuery1("INSERT TABLE NAME HERE"));
Related
I am very new to Java and am simply trying to connect to my MSSQL database and return a list of customers. When I try the JDBC connection, I get a "no suitable driver found" error. When I add a Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver") statement, I get a ClassNotFound error. This seems like it should be a lot easier than it's turning out to be. Please help me either find a suitable driver or how to get access through the Class.forName usage.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
public class DbConn {
public static String getConnString(){
return "jdbc:sqlserver://localhost\\SQLEXPRESS:1433;database=OhHold;";
}
public static void getConnection() {
try
{
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String user = "<USER>";
String pw = "****************";
Connection connection = DriverManager.getConnection(getConnString(), user, pw);
Statement statement = connection.createStatement();
String sql = "select txtCompanyName as company from tblCustomers where intNotActive <> 1";
ResultSet result = statement.executeQuery(sql);
while (result.next()) {
System.out.println(result.getString(1));
}
}
/*
// Handle any errors that may have occurred.
catch (ClassNotFoundException e) {
e.printStackTrace();
}
*/
catch (SQLException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
getConnection();
}
}
Can anybody help me to get actual column name and its alias using ResultSetMetaData by connecting to sqlserver database.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
class MysqlCon {
public static void main(String args[]) {
Connection con = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=alcoa", "sa", "test");
Statement stmt = con.createStatement();
String query = "SELECT std_code as \"Student code\" from Student ";
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsm =rs.getMetaData();
for (int i = 1; i <= rsm.getColumnCount(); i++) {
System.out.println(rsm.getColumnLabel(i) + "--" + rsm.getColumnName(i));
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
output
Student code--Student code
Above code works as expected in other database like mysql and oracle.
I checked code for SQLServerResultSetMetaData. Both methods getColumnLabel and getColumnName are identical.
abzycdxw65, has raised same issue on their github account. it is closed.
Is there any way to get following output:
Student code--std_code
If I get your question you can try the followings to retrieve column names
select name from sys.columns
I would like to make a mysql database query in a Java code and if the value from the database is true for example then a certain code should be executed and if the value is false the program should close but I have the problem that I get the value from the database is not formatted so that I can make an IF query. if I could not explain this in a very understandable way, I hope that you can find out from the code in the appendix
//imports
package de.alphaalmann.troll;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.sql.*;
public class Main extends JavaPlugin {
public static void main(String[] args) {
//databaseconnetion
String url = "jdbc:mysql://localhost/plugin?useJDBC";
String user = "plugin";
String password = "uwu3000";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("sucsesful");
PreparedStatement stmt = conn.prepareStatement("SELECT STATUS FROM plugin WHERE NAME="trollpl"");
stmt.execute();
System.out.println(stmt);
stmt.close();
//if-query if it true,
if(stmt==true) {
//if it true execute this
//else this part
}else {
System.out.println("error");
}
}catch(SQLException ex) {
System.err.println(ex.getMessage());
}
}
}
highling.
You'll need a ResultSet object in order to receive the query results, get the results and then close the PreparedStatement.
Something like this:
int result;
ResultSet rs = stmt.execute();
if(rs.next()){
// I don't know what your query returns
//I'll assume you use only the first result , it'll be an int
result = rs.getInt(1);
}
stmt.close();
// Now you decide what to do with result.
HTH,
WB::
I must encapsulate my access to the Oracle database in one java class, called dbconf:
package DB_Oracle_Connection;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class dbconf {
private String connstr;
private Connection connect;
private PreparedStatement prepstat = null;
public Connection getConnection() throws SQLException {
connstr = "jdbc:oracle:thin:#localhost:1521:orcl";
try {
String uname = "fred";
String pass = "flintstone";
Class.forName("oracle.jdbc.driver.OracleDriver");
connect = DriverManager.getConnection(connstr, uname, pass);
} catch (Exception e) {
System.out.println(e.toString());
}
if (connect != null) {
System.out.println("Connected to the database!");
} else {
System.out.println("Failed to make connection!");
}
return connect;
}
public PreparedStatement prepareStatement (Connection conn,String sql_code)
throws SQLException {
prepstat = conn.prepareStatement(sql_code);
return prepstat;
}
}
In my the second java class DB_Oracle_Insert_Statement i call dbconf.
package DB_Oracle_Connection;
import DB_Oracle_Connection.dbconf;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class DB_Oracle_Insert_Statement {
public static void main(String[] args) {
try {
dbconf connect = new dbconf();
// create our java preparedstatement using a sql update query
PreparedStatement ps = connect.prepareStatement((Connection) connect, "INSERT INTO MKR_TEST1 VALUES ( ?, ?, ? , ?)");
System.out.format("INSERT MKR_TEST1 VORNAME, NACHNAME, ADRESSE\n");
// set the preparedstatement parameters
ps.setString(1,"zzzzzVORNAME");
ps.setString(2,"zzzzzNACHNAME");
ps.setString(3,"zzzzADRESSE");
ps.setString(4,"11");
// call executeUpdate to execute our sql update statement
ps.executeUpdate();
//System.out.format("COMMIT\n");
//PreparedStatement ps1 = connect.prepareStatement(
// "COMMIT");
// call executeUpdate to execute our commit statement
//ps1.executeUpdate();
ps.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
My compiler eclpise says everything is fine with my code. But when I execute my code
Got an exception!
class DB_Oracle_Connection.dbconf cannot be cast to class
java.sql.Connection (DB_Oracle_Connection.dbconf is in module
DB_Oracle_Connection of loader 'app'; java.sql.Connection is in module
java.sql of loader 'platform')
How do I fix problem in my code ?
Your connectis not a class which implements the Connection interface which is expected by the prepared statement.
So change connect to connect.getConnection()
PreparedStatement ps = connect.prepareStatement(connect.getConnection(), "INSERT INTO MKR_TEST1 VALUES ( ?, ?, ? , ?)");
or use your private variable in your prepared statement method:
public PreparedStatement prepareStatement (String sql_code)
throws SQLException {
prepstat = connection.prepareStatement(sql_code);
return prepstat;
}
BTW: Take care of java naming conventions. Class names should start with upper case character
your class cannot be casted to a Connection class. It is not in the inheritance hierarchy. So to get the connection object correctly, just call your method getConnection() in this way in the class DB_Oracle_Insert_Statement
...
public static void main(String[] args) {
try {
dbconf connect = new dbconf();
// create our java preparedstatement using a sql update query
PreparedStatement ps = connect.prepareStatement(connect.getConnection(), "INSERT INTO MKR_TEST1 VALUES ( ?, ?, ? , ?)");
...
I am using a restful web service and I was able to display database records using an array. But I am confused on how will I be able to display my desired record. I have here the class where the SQL query is being executed. I am using Advanced Rest Client google chrome application in testing the response and the output. How will I be able to query 'select * from taxi where taxi_plate_no='inputted data''? I am really confused on how will I be able to do it in an array. Please help me. Thank you! :(
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.ws.rs.QueryParam;
import com.taxisafe.objects.Objects;
public class DisplayArrayConnection
{
public ArrayList<Objects> getDetails(Connection con) throws SQLException{
ArrayList<Objects> taxiDetailsList = new ArrayList<Objects>();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM taxi");
ResultSet rs = stmt.executeQuery();
try
{
while(rs.next())
{
Objects detailsObject = new Objects();
detailsObject.setTaxi_name(rs.getString("taxi_name"));
detailsObject.setTaxi_plate_no(rs.getString("taxi_plate_no"));
taxiDetailsList.add(detailsObject);
}
} catch (SQLException e)
{
e.printStackTrace();
}
return taxiDetailsList;
}
}
#QueryParam is annotation used in rest webservices .
And i think here you want to use parameter with your SQL query.
So using parameter in PreparedStatement use following code
public class DisplayArrayConnection
{
public ArrayList<Objects> getDetails(Connection con,String taxiNumber) throws SQLException{
ArrayList<Objects> taxiDetailsList = new ArrayList<Objects>();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM taxi WHERE taxi_plate_no= ?");
stmt.addString(1,taxiNumber);
ResultSet rs = stmt.executeQuery();
try
{
while(rs.next())
{
Objects detailsObject = new Objects();
detailsObject.setTaxi_name(rs.getString("taxi_name"));
detailsObject.setTaxi_plate_no(rs.getString("taxi_plate_no"));
taxiDetailsList.add(detailsObject);
}
} catch (SQLException e)
{
e.printStackTrace();
}
return taxiDetailsList;
}
}
Note: Use parameter taxiNumber or any other parameter you want to
retrive data on that parameter
and use setString(position,value); to replace ? with that parameter