I want to get a values from datareader, but there is an error called
"No data exists for the row/column".
this is my code
//select the group where status is active
OleDbCommand com2 = new OleDbCommand("select group from tblBillConfig where status=1 group by group",con);
OleDbDataReader dr2 = com2.ExecuteReader();
//int i = Convert.ToInt32(dr2);
string ii = dr2["group"].ToString();
MessageBox.Show(ii);
please anyone can help?
If your query doesn't return any record then you get that message.
You need to check if there are rows returned and then try to read them....
By the way, I am pretty sure that the word GROUP is a reserved keyword fow everyt SQL database system. To use it you should enclose it in square brakets (but that could be different for every database system)
OleDbCommand com2 = new OleDbCommand("select [group] from tblBillConfig " +
"where status=1 group by [group]",con);
OleDbDataReader dr2 = com2.ExecuteReader();
// This will load the first row, so you could get its value
if(dr2.Read())
{
string ii = dr2["group"].ToString();
MessageBox.Show(ii);
}
else
{
MessageBox.Show("Query doesn't return any rows");
}
Related
newbie here.. i have a two data sets which is "time-in", and "time-out" and i would like to query this two using "between" so that the data ive should get was the filtered on my "time-in" to my "time-out"...
this is my query data (get all data).
public Cursor retrieveHistoryLocationFromLocalDatabase(SQLiteDatabase db)
{
String[] columnNames =
{
HISTORY_SERIAL_NUMBER,
HISTORY_LATITUDE,
HISTORY_LONGITUDE,
HISTORY_DATE_TIME,
HISTORY_SPEED,
HISTORY_PORT
};
return (db.query(TABLE_HISTORY_FLEET_LOCATION, columnNames,null,
null,null, null, null));
}
Use rawQuery() method to prepare select statement.
public Cursor retrieveHistoryLocationFromLocalDatabase(SQLiteDatabase db, String timeIn, String {
String sql = "SELECT HISTORY_SERIAL_NUMBER, HISTORY_LATITUDE,"
+ " HISTORY_LONGITUDE, HISTORY_DATE_TIME, HISTORY_SPEED, HISTORY_PORT"
+ " FROM your_table_name"
+ " WHERE your_time_in_out_column BETWEEN '" + timeIn + "' AND '" + timeOut + "'";
return (db.rawQuery(sql, null));
}
You have to change your_table_name with your actual table name and your_time_in_out_column with actual column name and timeIn and timeOut variable type, values with your actual values.
While calling retrieveHistoryLocationFromLocalDatabase() method you need to pass 3 parameters SQLite database object, time-in and time-out.
PS: rawQuery() method is not recommended as it takes raw SQL statements as an argument. This poses SQL injection threat.
I'm trying to get a field to update with each line item on the invoice (without over writing what is already there), using a Query Expression to get the data that needs to be used to update the field.
So far I've been able to get this to work just fine when only 1 line item is present. But whenever I test this against multiple line items I get the " The given key was not present in the dictionary." error.
Any help or nudge in the right direction?
QueryExpression lineitem = new QueryExpression("invoicedetail");
lineitem.ColumnSet = new ColumnSet("quantity", "productid", "description");
lineitem.Criteria.AddCondition("invoiceid", ConditionOperator.Equal, invoiceid);
EntityCollection results = server.RetrieveMultiple(lineitem);
Invoice.Attributes["aspb_bookmarksandk12educational"] = "Purchases";
Invoice.Attributes["aspb_bookmarksandk12educational"] += "\n";
Invoice.Attributes["aspb_bookmarksandk12educational"] += "Product" + " " + "Quantity";
Invoice.Attributes["aspb_bookmarksandk12educational"] += "\n";
foreach (var a in results.Entities)
{
string name = a.Attributes["description"].ToString();
string quantity = a.Attributes["quantity"].ToString();
Invoice.Attributes["aspb_bookmarksandk12educational"] += " " + name + " ";
Invoice.Attributes["aspb_bookmarksandk12educational"] += quantity;
Invoice.Attributes["aspb_bookmarksandk12educational"] += "\n";
}
"The given key was not present in the dictionary."
Suggests the problem lies in the way you are trying to access attribute values and not with the multiple entities returned. When you try get an attribute value, try to check if the attribute exists before reading the value like so:
if (a.Attributes.ContainsKey("description"))
{
var name = a.Attributes["description"] as string;
}
Or even better use the SDK extension methods to help do the check and return a default value for you like so:
var name = a.GetAttributeValue<string>("description");
var quantity = a.GetAttributeValue<decimal>("quantity");
I have an Access database which I need to retrieve all fields except the first and last and display it in a JTable. Everything works perfectly fine when I create my Object[][] but when i return it, i get a NullPointerException. I tried to find where there could be a null value in the database by printing the whole object out but that works fine and no values are null. Why would returning the Object[][] give me a NullPointerException and how can i fix it?
the stack trace is:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
public Object [] [] SetTrainingLogTable() throws SQLException
{
DatabaseConnection connection = new DatabaseConnection();
//Retrieves all the data from the TrainingLog table
ResultSet resultset = connection.SelectStatements("SELECT * FROM TrainingLog");
//Retrieves the number of entries
ResultSet numberofworkouts = connection.SelectStatements("SELECT COUNT(*) FROM TrainingLog");
int count = numberofworkouts.getInt(1);
number = count;
String[][] table = new String [count] [6];
//Number to incriment for while loops
int row = 0;
String date = "";
while(row<count)
{
date = resultset.getString(2);
table [row][0] = calculate.RefineDate(date);
table [row][1] = resultset.getString(3);
table [row][2] = resultset.getString(4);
table [row][3] = resultset.getString(5);
table [row][4] = resultset.getString(6);
table [row][5] = resultset.getString(7);
resultset.next();
row++;
}
Object[][] data = table;
connection.close();
return data;
}
I ran a debugger and it only gives the error when the return line is run.
It's best to post the stack trace and tell which line is raising the error. However, the typical way of writing such code is:
Connection con = ...;
Statement st = ...;
ResultSet rs = ...;
while (rs.next()) {
// ...
}
The result set starts out pointing before the first row. rs.next() returns whether there is a next row, and advances to it if it exists. Can you rewrite it in that style?
Other suggestions:
Can you create an actual object type instead of using Object[] to store the data from each row? Call it Workout.
Can you use a List<Workout> instead of your Object[][]?
Is the date stored in the database as a SQL DATE or TIMESTAMP? Then, don't convert it to a Java String: use java.sql.Date or java.util.Date. At work, I have a large old program that uses strings for dates, and it uses different formats to convert the values at different times. It's pretty miserable.
Don't use SELECT *. Give the names of the columns to return. Use the rs.getString("column_name") syntax.
There's no need to set one variable to the returned table and immediately set another variable to it.
Closing the connection or statement should be done in a finally block, or by try-with-resources.
Hi I'm just learning C# and am struggling with a problem and would appreciate any help I can get.
My first problem is this, I have an aspx form that when you hit the save button it inserts data into 2 separate tables, [Transaction and TransactionDetails] both tables contain TransID fields defined as Guids. The Transaction tables Guid is also the primary key. My question is how do I insert the same guid (TransID) which is a uniqueidentifier into both tables.... then at the same time(that's my hope) I have a stored proc that needs to be run that requires that same Guid as a parameter. So in short I need the same GUID in both tables and have to pass the newly created Guid to my stored procedure.
Here's my code code so far, can you help me with what I need to add or change to make that happen.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection((System.Configuration.ConfigurationManager.ConnectionStrings["NovaConnectionString"].ConnectionString));
sc.Open();
string insertSQL;
insertSQL = "INSERT INTO [Transaction] (";
insertSQL += "TransactionID, FileNumber, TransactionDate, RegistryID, InstrumentID, TransactionTypeID, CompanyID, ";
insertSQL += "InvoiceNo, Unit, Price, DueDiligance, Legal)";
insertSQL += "VALUES (";
insertSQL += "#TransactionID, #FileNumber, #TransactionDate, #RegistryID, #InstrumentID, #TransactionTypeID, #CompanyID, ";
insertSQL += "#InvoiceNo, #Unit, #Price, #DueDiligance, #Legal)";
//string query1 = String.Format(#"Insert Into Transaction (TransactionID, FileNumber, TransactionDate, RegistryID, InstrumentID, TransactionTypeID, CompanyID, InvoiceNo, Unit, Price, DueDiligance, Legal)"
//+ " VALUES (#TransactionID, #FileNumber, #TransactionDate, #RegistryID, #InstrumentID, #TransactionTypeID, #CompanyID, #InvoiceNo, #Unit, #Price, #DueDiligance, #Legal)");
SqlCommand cmd = new SqlCommand(insertSQL, sc);
SqlCommand cmd3 = new SqlCommand("uspProcessPurchasedOffsets", sc);
cmd3.CommandType = CommandType.StoredProcedure;
//Add the parameters.
cmd.Parameters.AddWithValue("#TransactionID", Guid.NewGuid());
cmd.Parameters.AddWithValue("#FileNumber", txtFileNumber.Text);
cmd.Parameters.AddWithValue("#TransactionDate", txtTransactionCreated.Text);
cmd.Parameters.AddWithValue("#RegistryID", ddlRegistry.Text);
cmd.Parameters.AddWithValue("#InstrumentID", ddlInstrument.Text);
cmd.Parameters.AddWithValue("#TransactionTypeID", txtTransactionTypeID.Text);
cmd.Parameters.AddWithValue("#CompanyID", ddlCompany.Text);
cmd.Parameters.AddWithValue("#InvoiceNo", txtInvoiceNo.Text);
cmd.Parameters.AddWithValue("#Unit", txtTotalVolume.Text);
cmd.Parameters.AddWithValue("#Price", txtPrice.Text);
cmd.Parameters.AddWithValue("#DueDiligance", txtDueDiligance.Text);
cmd.Parameters.AddWithValue("#Legal", txtLegal.Text);
//Parameter for stored Proc
cmd3.Parameters.Add("#TransactionID", SqlDbType.UniqueIdentifier);
cmd.ExecuteNonQuery();
string insertSQL2;
insertSQL2 = "INSERT INTO [TransactionDetails] (StartSerialNumber,VintageYear,Units)";
insertSQL2 += "VALUES (#StartSerialNumber, #VintageYear, #Units)";
SqlCommand cmd1 = new SqlCommand(insertSQL2, sc);
//Add the parameters.
cmd1.Parameters.AddWithValue("#StartSerialNumber", txtStartSerial.Text);
cmd1.Parameters.AddWithValue("#VintageYear", txtVintage.Text);
cmd1.Parameters.AddWithValue("#Units", txtVolume.Text);
cmd1.ExecuteNonQuery();
cmd3.ExecuteNonQuery();
}
}
I think you could store the GUID in an appropriate intermediate variable and then pass the same variable to yours parameters for the storedprocedure and for the commandtext
Guid g = Guid.NewGuid();
cmd.Parameters.AddWithValue("#TransactionID", g);
.....
cmd3.Parameters.Add("#TransactionID", SqlDbType.UniqueIdentifier, 16 ).Value = g;
I am getting the result set in an array. Now I am trying to access the id that is the first index of the array but getting an error. Please let me know how to access the indexes of array.
$email_template = DB::query(Database::SELECT,"select * from mail_settings where id = " .$email['id'])->execute();
When you just run the execute method on a query, you get back a Database_MySQL_Result object.
To return an array instead, use the as_array method like so:
$email_template = DB::query(Database::SELECT,
"select * from mail_settings where id = " .$email['id'])
->execute()->as_array();
Now you will be able to access the resultset as an array.
If all you want/need is the first or current row from the query, you can use the current method which you can read more about in the Kohana_Database_MySQL_Result class:
$email_template = DB::query(Database::SELECT,
"select * from mail_settings where id = " .$email['id'])
->execute()->current();
You are getting a Database_MySQL_Result object, not an array.
This will be correct.
$email_template = DB::query(Database::SELECT,
"select * from mail_settings where id = " .$email['id'])
->execute()->current();