java program only gives first column of database table "Users" MSSQL - java

I am having an issue where i connect to the database,but cannot retrieve more than the first column even though my query statement is "Select * from Users"
below is my code:
import java.sql.*;
public class Connecttodb {
public void dbConnect(String db_connect_string,String db_UserID,String db_UserPass)
{
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,db_UserID,db_UserPass);
System.out.println("connected");
Statement statement= conn.createStatement();
String querystring = "SELECT * FROM Users";
ResultSet rs = statement.executeQuery(querystring);
while(rs.next()){
System.out.println(rs.getString(1));
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Connecttodb connServer= new Connecttodb();
connServer.dbConnect("jdbc:sqlserver://TGOURDINE-PC\\SQLEXPRESS;databaseName=picture website", "tgourdine", "thomas");
}
}
the result is only the first column, UserID:
connected
1
2
3
The result i want is as follows:
connected
1 tgourdini thomas NULL NULL
2 Geoff Marley NULL NULL
3 tara Elaine NULL NULL
thank you,

According to the documentation getString(1) will return only the first column.

Because you only retrieve the first column
System.out.println(rs.getString(1));
Change your loop to
while(rs.next())
System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4));
Have a look at the documentation of getString
Retrieves the value of the designated column in the current row of
this ResultSet object as a String in the Java programming language.
Also have a look at the received parameter documentation
columnIndex - the first column is 1, the second is 2, ...

Related

load data from database to another one using java

I have an old database and i want to load the new data from that database every hour into a new database (That i created) using a java code..
i tested that just in two simple databases using this code but it doesn't work for me , can any of u help me or give me some ideas:
import java.sql.*;
class DB{
public static void main(String args[]) {
try {
//loading the jdbc driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/b", "root", "");
Statement stmt = con.createStatement();
//int rows = stmt.executeUpdate("INSERT INTO b.table2 SELECT * FROM a.table1");
ResultSet rs = stmt.executeQuery("INSERT INTO b.table2 SELECT * FROM a.table1");
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4));
con.close();
} catch (Exception e) {
System.out.println(e);
}
}}
Your code as printed will work fine. INSERT statements do not return a resultset; they return a single number that represents how many rows were affected. Your commented out code is therefore correct; your uncommented line (using .executeQuery) isn't useful here and probably won't work.

ResultSet returns empty despite query correctly producing results in SQLiteStudio

Context:
Local database made with sqlite3 called lims.db which contains a table called privLevels with columns user storing usernames and level storing integers from 0 to 2, but as a string.
privLevels
~~~~~~~~~~~~~~
user | level
~~~~~~~~~~~~~~
admin | 0
john | 1
kevin | 2
susan | 1
I'm trying to run and SQL SELECT query on this table and then pass the results into a Map object, with the values from user being the key, and values from level being the value.
privMap
~~~~~~~~~~~~~~~
<"admin" = "0">
<"john" = "1">
<"kevin" = "2">
<"susan" = "1">
The problem I'm having is that the ResultSet generated is returned as completely empty. The while loop in the code below never runs, and in the IntelliJ debugger, the ResultSet object is empty. In SQLiteStudio, the query runs correctly. In the rest of my code, statements run fine, but queries don't.
Code:
getPrivMapFromDatabase() should work - if the ResultSet contained anything. It gets the value from user and level and then .puts() them into the Map.
public void getPrivMapFromDatabase() {
ResultSet results = Base.getStringMapFromDatabase("privLevels", "user", "level");
try {
while(results.next()) {
String user = results.getString("user");
System.out.println(user);
String level = results.getString("level");
System.out.println(level);
privMap.put(user, level);
}
}
catch (SQLException e) {
System.out.println("[EXCEPTION] " + e.getMessage());
e.printStackTrace();
}
}
These methods are in the "Base" class.
I wrote getStringMapFromDatabase() like this because I need to do the same thing to another table and map. It should generate the string (which I checked is syntactically correct) and then execute it.
executeQuery() should just run the query and then return the ResultSet to getPrivMapFromDatabase(). However, the ResultSet object is empty. CREATE / INSERT statements work fine (using a seperate methods for running statements).
private static String url = "jdbc:sqlite:C:/Users/#My_Username#/IdeaProjects/#Project_Name#/sqlite/db/lims.db";
//Username and project name redacted
public static ResultSet getStringMapFromDatabase(String table, String keyColumn, String valueColumn) {
String sql = "SELECT " + keyColumn + ", " + valueColumn + " FROM " + table + ";";
return executeQuery(sql);
}
public static ResultSet executeQuery(String sql) {
ResultSet results = null;
try (Connection connection = DriverManager.getConnection(url);
Statement statement = connection.createStatement()) {
results = statement.executeQuery(sql);
}
catch (SQLException exception) {
System.out.println("[EXCEPTION] " + exception.getMessage());
}
return results;
}
Why is the ResultSet coming back empty, even though the query runs fine in SQLiteStudio and other statements work? The table name, and column names are correct.

not all variables bound when returning inserted id Oracle

I'm trying to get the new id when inserted new data in database table, but I got:
ORA-01008: not all variables bound
I'm doing it from a Java SE project,
public ResultSet ejecutarConsulta(String instruccionSql){
rs = null;
try {
st = con.createStatement();
rs = st.executeQuery(instruccionSql);
System.out.println("Consulta Exitosa");
} catch (SQLException e) {
System.out.println("Error en la Consulta: "+e.getMessage());
}
return rs;
}
And the String "instruccionSql" that i'm passing is
insert into Usuario(DOCUMENTOIDENTIDAD,NOMBRE,CARGO,CONTRASENA,PERMISO)
values ('22323','asfa','Administrador','123456','0')
RETURNING ID INTO :temp
I have the corresponding trigger and Seq to generate the table autoincrement id.
Use CallableStatement and register the OUT parameter.
This is an excellent opportunity to register the IN parameters too.
String mySql = "DECLARE x NUMBER; BEGIN "
+ " insert into Usuario(DOCUMENTOIDENTIDAD,NOMBRE,CARGO,CONTRASENA,PERMISO) "
+ " values (?,?,?,?,?) "
+ " RETURNING ID INTO x;"
+ " ? := x;"
+ "END; ";
CallableStatement cal = conn.prepareCall(mySql);
cal.setString(1, "22323");
cal.setString(2, "asfa");
cal.setString(3, "Administrador");
cal.setString(4, "123456");
cal.setString(5, "0");
cal.registerOutParameter(6, java.sql.Types.INTEGER);
cal.executeQuery();
Integer newId = cal.getInt(6);
you are attempting to use a bind variable (:i) that is not bound to a value.

net.ucanaccess.jdbc.UcanaccessSQLException: Column not found: 0

I am new for UCanAccess
package checktpsystemdatabase;
import java.sql.*;
public class CheckTPSystemDatabase {
public static void main(String[] args) throws SQLException {
try {
Connection con = DriverManager.getConnection("jdbc:ucanaccess://D:/Java/TransactionProcessingSystem/src/transactionprocessingsystem/Resources/TPSystem.accdb");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Product");
while (rs.next()) {
System.out.println(rs.getInt(0) + "\t" + rs.getString(1) + "\t" + rs.getString(2));
}
rs.close();
} catch (SQLException e) {
System.out.println(e);
}
}
}
When I execute this code, It is showing "net.ucanaccess.jdbc.UcanaccessSQLException: Column not found: 0". Please help me!
You are seeing that error because the numeric index values for a JDBC ResultSet start with 1, not 0. Or, as they say in the "Retrieving Column Values from Rows" section of the Java Tutorial here:
The ResultSet interface declares getter methods (for example, getBoolean and getLong) for retrieving column values from the current row. You can retrieve values using either the index number of the column or the alias or name of the column. The column index is usually more efficient. Columns are numbered from 1
(Emphasis mine.)
simply
the ResultSet rs begins with index 1 not 0 so you should write rs.getInt(1) or rs.getObject(1)

JDBC's rs.getString() won't return the value of the query result

I have some problems with JDBC's rs.getString("column_name") basically it would not assign the value recieved from the query result, I have a String ris which is supposed to get the row name from rs.getString, for semplicity of the question I'm using ris and my query returns only one row. This is the code:
//It returns null, or any other values I use to initialize the variable
String ris=null;
q = "SELECT DISTINCT nome FROM malattia WHERE eta='" + age + "' AND sesso='" + sexstr + "' AND etnia='" + etniastr + "' AND sintomi IN(" + tes + ")";
ResultSet rs = st.executeQuery(q);
if (!rs.last()) {
ris = "no";
}
else {
//This is the place where I'm having problems
while(rs.next()){
//ris is supposed to get the name of the query result having column "nome"
ris=rs.getString("nome");
}
}
conn.close();
} catch (Exception e) {
ris = e.toString();
}
return ris;
I semplified the code, so it would be easy to focus on where the problem is.
Thanks in advance!
if (rs.last())
while (rs.next())
That won't work, because after you have called last , you are at the last row and next will always return false (it would return true and take you to the next row if there was one left).
And please use a prepared statement with bind variables!
And finally close ResultSet and Connection (or use Jakarta Commons DbUtils).
try this, just remove the rs.last() call in the if condition.. also i agree with #Thilo about using prepared statements.
String ris=null;
q = "SELECT DISTINCT nome FROM malattia WHERE eta='" + age + "' AND sesso='" + sexstr + "' AND etnia='" + etniastr + "' AND sintomi IN(" + tes + ")";
ResultSet rs = st.executeQuery(q);
rs.first(); // go to first record.
//This is the place where I'm having problems
while(rs.next()){
//ris is supposed to get the name of the query result having column "nome"
ris=rs.getString("nome");
}
}
conn.close();

Categories

Resources