I use JDBC to get data from sqlite data base. In DB I have 3 column - login, password and role. I try find row by login, but it doesn't work , and I have exeption when I try getString("password") or "role", where is the mistake? Thanks
resSet = statmt.executeQuery("SELECT * FROM users WHERE login='"+login+"';");
if( hasUser( login)){
System.out.println("User finded:");
while(resSet.next()) {
System.out.println("login = " + resSet.getString("login"));
// !exeption
System.out.println("password = " + resSet.getString("password"));
// !exeption
System.out.println("role = " + resSet.getString("role"));
System.out.println();
}
}else{
System.out.println( "User not found");
}
You can check to see what column names are being returned.
ResultSetMetaData rsmd = resSet.getMetaData();
int colCount = rsmd.getColumnCount();
String rValue = "";
for (int i = 1; i <= colCount ; i++){
String name = rsmd.getColumnName(i);
rValue += name + " ";
}
System.out.println(rValue);
ResultSetMetaData metaData = resultSet.getMetaData();
int count = metaData.getColumnCount(); //number of column
String columnName[] = new String[count];
for (int i = 1; i <= count; i++)
{
metaData.getColumnLabel(i));
}
Refer to this ans..ans see what are the names of your columns in resultant set
http://stackoverflow.com/questions/19094999/java-how-to-get-column-name-on-result-set
Related
I really need help. I am trying to retrieve a data from in my database using ResultSetMetaData and ResultSet. Also I am using a stored Procedure. The program is run find, however when I run it and be expecting 3 result from the row, instead it will give me 2. For example if I ask a user to enter a position and there are 6 player in that position, it will give me 5 players instead of 6 player.
Here is my code
if (!rs.next()) {
System.out.println("There is no match in the database " + position);
}
else {
System.out.println(String.format(" " + " %-19s %s", "Name",
"Rank") + "\t" + String.format("%-11s %s", "Position",
"School") + "\t" + String.format("%-6s %s",
"Age", "War") + "\n-----------------"
+ "-------------------------------------------------");
while (rs.next()) {
int rank = 0, age = 0;
String name = null, pos = null, sch = null;
double war = 0;
for (int i = 1; i < colum - 1; i++) {
rank = rs.getInt(1);
name = rs.getString(2);
pos = rs.getString(3);
sch = rs.getString(4);
age = rs.getInt(5);
war = rs.getDouble(6);
}
When I run my java code I get this result. It's not getting the first index in the list
When I call my stored procedure in MYSQL Workbench, I get this result
You have read first index in
if (!rs.next()) {
itself. This will move the cursor to the next row. You will have to remove this and it will give all the rows.
am trying to edit and update jtable cells as in my code below. my problem is that a single row when updated all the other rows get the same values. i mean only one row is updated and all other a duplicated. can any one help with a good approach. thanks
int count = Table_purchase.getRowCount();
int col = Table_purchase.getColumnCount();
String pod_id[] = new String[count];
String po_id[] = new String[count];
String order_qty[] = new String[count];
String item_id[] = new String[count];
String unit_price[] = new String[count];
String recived_qty[] = new String[count];
String rejected_qty[] = new String[count];
for (int i = 0; i < count; i++) {
po_id[i] = Table_purchase.getValueAt(i,0).toString();
pod_id[i] = Table_purchase.getValueAt(i,1).toString();
order_qty[i] = Table_purchase.getValueAt(i,2).toString();
item_id[i] = Table_purchase.getValueAt(i,3).toString();
unit_price[i] = Table_purchase.getValueAt(i,4).toString();
recived_qty[i] = Table_purchase.getValueAt(i, 5).toString();
rejected_qty[i] = Table_purchase.getValueAt(i,6).toString();
try {
String sql = "update purchase.purchase_detail set pod_id='" + pod_id[i] + "',order_qty='" + order_qty[i] + "',item_id='" + item_id[i] + "', unit_price='" + unit_price[i] + "', recived_qty='" + recived_qty[i] + "',rejected_qty='" + rejected_qty[i] + "'where po_id= '" + po_id[i] + "'";
pst = conn.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(null, "updated");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
Your sql statement does not contain a where-clause, hence all rows in the database table are updated for each iteration of the swing-table-rows, and in the end, all the database-rows will have the values from the last swing-table-row.
(And, use pst.setParameter (http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html) and do not mix sql into gui-code.)
I have an ArrayList as shown below
import java.util.ArrayList;
public class Mann {
public static void main(String args[]) {
ArrayList<String> billOrderList = new ArrayList<String>();
list.add("VAT");
list.add("Discount");
list.add("SERVICE CHARGE");
StringBuilder select_query = new StringBuilder();
select_query.append("Select ");
for (int i = 0; i < billOrderList.size(); i++) {
if (i != billOrderList.size() - 1) {
select_query.append("" + billOrderList.get(i) + " , ");
} else {
select_query.append("" + billOrderList.get(i) + "");
}
}
select_query.append(" From VENDOR_ITEMS WHERE vendor_items_id = "
+ vendor_item + "");
VendorItems_Pstmt = dbConnection.prepareStatement(select_query
.toString());
VendorItems_RSet = VendorItems_Pstmt.executeQuery();
while (VendorItems_RSet.next()) {
String tax_name = VendorItems_RSet.getString();
}
}
}
How can i give the column name which is dynamic in this case in line VendorItems_RSet.getString();??
You need as ResultSetMetaData to get the column name associated with your query result.
You can get ResultSetMetaData from ResultSet by using ResultSet.getMetaDate, you can iterate it and get column all column name.
ResultSetMetaData VendorItems_RSet_metaData = VendorItems_RSet.getMetaData();
int numberOfColumns = VendorItems_RSet_metaData .getColumnCount();
for(int i=1;i<=numberOfColumns;i++)
{
String columnName = VendorItems_RSet_metaData.getColumnName(i);
}
I think you need all column data for that you can iterate your loop like
while (VendorItems_RSet.next())
{
for(int i=1;i<=numberOfColumns;i++)
{
String columnName = VendorItems_RSet_metaData.getColumnName(i);
String tax_name = VendorItems_RSet.getString(columnName);
System.out.println(tax_name);
}
}
ResultSetMetaData resultSetMetaData = VendorItems_RSet.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
String type = resultSetMetaData.getColumnTypeName(i); // Get Column type
String name= resultSetMetaData.getColumnName(i); //Column name
}
}
SELECT * and then
ResultSetMetaData metaData = VendorItems_RSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; ++i) {
System.out.println(metaData.getColumnName(1));
}
I am actually building a project where the names of tables present in databases of mysql are displayed in a list in java.
user selects a table from a list and the description of that table in given using "desc tablename" command.
The problem is, it is supposed to get every field in table but it only gets first field. Below i have explained it more, but first heres my code-:
try {
int rowCount = tableModel.getRowCount();
for (int i = 0; i < rowCount; i++) {
tableModel.removeRow(i);
}
String z = jList2.getSelectedValue().toString();
try {
Class.forName("java.sql.DriverManager");
} catch (ClassNotFoundException e) {
timeget();
jTextArea4.append(now + ": " + "/ Failed in getting Driver \n Error Message: " + e.getMessage() + " / \n \n");
JOptionPane.showMessageDialog(this, e.getMessage());
}
DriverManager.getConnection("jdbc:mysql://localhost:" + GlobalParams.portvar + "/", "" + k, "" + j);
stmnt = (Statement) con.createStatement();
String query = "desc " + z;
jTextArea5.append(now + ": " + "/ desc " + z + "; / \n \n");
ResultSet rs = stmnt.executeQuery(query);
String[] cnames = {"Field", "Type", "Null", "Key", "Extra"};
tableModel.setColumnIdentifiers(cnames);
jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
jTable1.setFillsViewportHeight(true);
if (rs.next()) {
String field = rs.getString("Field");
String type = rs.getString("type");
String nullinfo = rs.getString("null");
String key = rs.getString("key");
String extra = rs.getString("extra");
tableModel.addRow(new Object[]{field, type, nullinfo, key, extra});
}
catch(SQLException e){//some blabla}
Now for detailing into problem->
Say from the list, i select a table called "city". Originally, it has four fields- ID, Name, Population, CountryCode. But in my jTable, only "ID" appears.
the code...
int rowCount = tableModel.getRowCount();
for (int i = 0; i < rowCount; i++) {
tableModel.removeRow(i);
}
...is simply to remove fields of old table when a new table is selected from list.
Hope i clarified my prob.
Please help regarding this. Thanks.
the problem is in this
if (rs.next()) {
String field = rs.getString("Field");
String type = rs.getString("type");
String nullinfo = rs.getString("null");
String key = rs.getString("key");
String extra = rs.getString("extra");
tableModel.addRow(new Object[]{field, type, nullinfo, key, extra});
}
you are not continuing the loop
change the if loop to while loop
while(rs.next()) {
String field = rs.getString("Field");
String type = rs.getString("type");
String nullinfo = rs.getString("null");
String key = rs.getString("key");
String extra = rs.getString("extra");
tableModel.addRow(new Object[]{field, type, nullinfo, key, extra});
}
This question already has answers here:
Retrieve column names from java.sql.ResultSet
(14 answers)
Closed 8 years ago.
Hello I'm trying to make an error when there is no matched student...
and it will display like this
No matching records found and I want the column name still the same but still not figuring it out... can some one tell me if this is right??
Heres my function for that... and I add comment there where I put the error... but i don't know how to get the columnname
public void SearchTableStudent() {
String tempSearchValue = searchStudent.getText().trim();
boolean empty = true;
sql = "SELECT student_id as 'Student ID',"
+ "concat(lastname, ' , ', firstname, ' ', middlename) as 'Name'"
+ "FROM user "
+ "WHERE CAST(student_id as CHAR) LIKE '%" + tempSearchValue + "%'";
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()) {
table.setModel(DbUtils.resultSetToTableModel(rs));
empty = false;
}
if(empty) {
String error = "";
table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"No matching records found",null}
},
new String [] {
/** I WANT TO PUT THE SAME COLUMN NAME ON MY DATABASE SELECTED BUT DON't Know
WHAT FUNCTION TO DO*/
}
));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
I try like this but still gave me NULL!!!
this code is below of empty = false;
for(int i=0; i<table.getColumnCount(); i++) {
test[i] = table.getColumnName(i);
}
ResultSetMetaData metaData = resultSet.getMetaData();
int count = metaData.getColumnCount(); //number of column
String columnName[] = new String[count];
for (int i = 1; i <= count; i++)
{
columnName[i-1] = metaData.getColumnLabel(i);
System.out.println(columnName[i-1]);
}
Try this.
ResultSetMetaData meta = resultset.getMetaData();
Integer columncount = meta.getColumnCount();
int count = 1 ; // start counting from 1 always
String[] columnNames = new String[columncount];
while(count<=columncount){
columnNames [count-1] = meta.getColumnLabel(count);
count++;
}
Since here your expecting is to get the columns alias instead of column name, so you have to use ResultSetMetaData.getColumnLabel instead of ResultSetmetaData.getColumnName.
Get ResultSetMetaData using ResultSet#getMetaData():
ResultSetMetaData meta = rs.getMetaData();
And then to get column name of 1st column:
String col1Name = meta.getColumnLabel(1);
Similarly to get column name of 2nd column:
String col2Name = meta.getColumnLabel(2);
Get the metadata
ResultSetMetaData metaData = rs.getMetaData();
Then you can do:
String columnName = metaData.getColumnName(int index);
ResultSetMetaData doc
rs.getMetaData().getColumnName(int i);
and do not concat the query param!