I have sample codes as below:-
public List<Announcement_User> announcementUser([FromBody]MyAnnouncementUser value)
{
MySqlConnection conn = WebApiConfig.conn();
MySqlCommand query = conn.CreateCommand();
query.CommandText = "select a.title,a.description,a.date_created,ua.read,ua.announcement_id,ua.user_announcement_id from announcement a left join user_announcement ua on a.announcement_id = ua.announcement_id where ua.user_id = #user_id";
query.Parameters.AddWithValue("#user_id", value.user_id);
var prodWishlist = new List<Announcement_User>();
try
{
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
prodWishlist.Add(new Announcement_User(null, null,null, false, 0, 0, ex.ToString()));
}
MySqlDataReader fetch_query = query.ExecuteReader();
while (fetch_query.Read())
{
prodWishlist.Add(new Announcement_User(fetch_query["title"].ToString(), fetch_query["description"].ToString(), fetch_query["date_created"].ToString(), (bool)fetch_query["read"], fetch_query.GetInt32(4), fetch_query.GetInt32(5), null));
}
conn.Close();
return prodWishlist;
}
And I hit error as below:-
"Message": "An error has occurred.",
"ExceptionMessage": "Specified cast is not valid.",
"ExceptionType": "System.InvalidCastException",
Now I suspect the error caused by bool. May I know how can I write correct way for bool in(fetch_query.Read())? Please help. Thank you.
Try using the GetBoolean method:
fetch_query.GetBoolean("read")
I would recommend to you to retrieve all of the values beforehand using column name instead of column index and create new object when required parameters have values:
string title = fetch_query["title"].ToString();
string description = fetch_query["description"].ToString();
// ...
object read = fetch_query["read"];
object integer1 = fetch_query[4];
// ...
// newest C# approach
if ( read != null && bool.TryParse(read.ToString(), out bool b_read) )
// old c# approach
bool b_read = false;
if ( read != null && bool.TryParse(read.ToString(), out b_read) )
Check for every required property
prodWishlist.Add(
new Announcement_User(
title,
description,
// ..
b_read,
i_integer1
//...
));
Related
I have been trying to update a record in the database in window form but each time I click the update button I get this error.
System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.' SqlException: Violation of PRIMARY KEY constraint 'PK_ad_gb_rsm'. Cannot insert duplicate key in object 'dbo.ad_gb_rsm'. The duplicate key value is (100001).
The statement has been terminated.
Below is the LINQ code I am using
private void btu_Update_Click(object sender, EventArgs e)
{
if (radioButtonMale.Checked)
{
gender = "male";
}
else if (radioButtonFemale.Checked)
{
gender = "female";
}
userID = Convert.ToDecimal(txtUserID.Text);
//ad_gb_rsm acc = DBS.ad_gb_rsm.First(s => s.ICube_id.Equals(userID));
var query = (from upd in DBS.ad_gb_rsm where upd.ICube_id == userID select upd).ToList();
foreach (var acc in query)
{
acc.user_type = comboBoxUser_Type.Text;
acc.JDate = dateTimeCrtDate.Text;
acc.title = comboBoxTitle.Text;
acc.fName = txtFname.Text;
acc.mName = txtMName.Text;
acc.lName = txtLName.Text;
acc.DOB = dateTimeDOB.Value.ToString();
acc.Gender = gender;
acc.Phone = txtPhoneNumber.Text;
acc.zip_code = txtZipCode.Text;
acc.POB = txtPOBAddress.Text;
acc.address = txtAddress.Text;
acc.email = txtEmail.Text;
acc.City = txtCity.Text;
acc.State = txtState.Text;
acc.marrital_Status = comboBoxMS.Text;
acc.NOK_Name = txtNKName.Text;
acc.NOK_Phone = txtNKNumber.Text;
acc.NOK_Address = txtNOKAddress.Text;
acc.NOKRela = txtNOKRela.Text;
acc.create_dt = dateTimeCrtDate.Value.ToString();
Image img = LogUserImage.Image;
if (img.RawFormat != null)
{
if (ms != null)
{
img.Save(ms, img.RawFormat);
acc.Picture = ms.ToArray();
}
}
acc.Dept_Sector = comboBoxDeptSector.Text;
acc.Position = comboBoxPosition.Text;
acc.JDate = dateTimeJoinDt.Value.ToString();
acc.Empl_Status = comboBoxUserStatus.Text;
acc.username = txtUsername.Text;
acc.password = txtPassword.Text;
acc.incu_copany_name = txtIncu_CompanyName.Text;
acc.createdBy = AdministratorBankLogin.AdminUserLogin.Username;
try
{
DBS.ad_gb_rsm.Add(acc);
DBS.SaveChanges();
MessageBox.Show("User Created Successfully");
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
}
I do not know what I am doing wrong. I am new to this.
The inner exception says everything:
SqlException: Violation of PRIMARY KEY constraint 'PK_ad_gb_rsm'. Cannot insert duplicate key in object 'dbo.ad_gb_rsm'. The duplicate key value is (100001)
Your code tried to perform an INSERT operation, but failed because it violates the unique constraint of the primary key.
The root cause of your problem is the following line:
DBS.ad_gb_rsm.Add(acc);
Because of the Add call your acc entity's state become Added rather than Modified. If you delete that Add method call then it will treat that entity as Modified and will perform an UPDATE operation.
If this change tracking concept is new to you then please read this MDSN article.
I have a SQLite database that returns 1 number to
Select value from Income where symbol = "AE" and statementitem = "Revenues" and periodtype = "Annual" and yearmonth = "Dec 2019"; --1811.2
I use a bit of c# code to test this to make sure nothing is missed:
public string GetIncome(string dbFile, string symbol, string aq, string yearmonth)
{
var answer = String.Empty;
try
{
using (var con = new SQLiteConnection($"URI=file:{dbFile}"))
{
con.Open();
using var cmd = new SQLiteCommand(con)
{
CommandText = $"Select value from Income where symbol = '{symbol}' and statementitem = 'Revenues' and periodtype = '{aq}' and yearmonth = '{yearmonth}';"
};
using SQLiteDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
answer = dataReader.GetString(1);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw ex;
}
return answer;
}
This errors out with System.IndexOutOfRangeException : Index was outside the bounds of the array.
Whats the best way to pick up on that value please?
See official docs:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.data.sqlite.sqlitedatareader.getstring?view=msdata-sqlite-3.1.0#Microsoft_Data_Sqlite_SqliteDataReader_GetString_System_Int32_
It tells that GetString only argument is "The zero-based column ordinal". In your case you're trying to access second item (by index 1), but your query has only single field returned. Use index 0 in
answer = dataReader.GetString(0);
I'm trying to get all string type rows with specified id from a table.
I keep getting the error Object reference not set to an instance of an object..
I tried try {} catch {} to see if there was a more detailed exception, which there wasn't.
This is what I've got.
var ReadReasons = _db.CreateCommand();
ReadReasons.CommandText = $"SELECT reason FROM Warns WHERE id = '{user}' AND guildId = '{guild}'";
SqliteDataReader ReadReasonData = await ReadReasons.ExecuteReaderAsync();
if (ReadReasonData.HasRows)
{
while (ReadReasonData.Read())
{
foreach (var reas in ReadReasonData)
{
ReadWarnReason.Add((string)reas);
}
}
}
I have a stored procedure call that goes like this:
using (OracleConnection con = new OracleConnection(ConfigurationManager.AppSettings["Database"]))
using (OracleCommand cmd = new OracleCommand("Package.Procedure", con))
{
Int32 existsCount;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("successCount", OracleDbType.Int32, 0, ParameterDirection.InputOutput);
cmd.Parameters.Add("BusinessId", OracleDbType.Int64, listRec.BusinessId, ParameterDirection.Input);
con.Open();
cmd.ExecuteScalar();
con.Close();
existsCount = Convert.ToInt32(cmd.Parameters["successCount"].Value);
return (existsCount);
}
But on this line:
existsCount = Convert.ToInt32(cmd.Parameters["successCount"].Value);
It throws the Exception "Unable to cast object of type 'Oracle.DataAccess.Types.OracleDecimal' to type 'System.IConvertible'."
Any thoughts? Thanks.
You can also try:
Oracle.DataAccess.Types.OracleDecimal d = (Oracle.DataAccess.Types.OracleDecimal)cmd.Parameters["successCount"].Value;
if( d.IsNull )
existsCount = 0;
else
existsCount = d.ToInt32( );
What about
existsCount = int.Parse(cmd.Parameters["successCount"].Value.ToString());
It is more efficient to use
Convert.ToInt32((decimal)(OracleDecimal)(cmd.Parameters["successCount"].Value))
I don't know the return type at runtime because the execution code is within a cross-platform data access framework under development, so I used a switch on the parameter value type to access the underlying Oracle[type].Value property for the various Oracle managed data access types.
public override object GetValue(IDataParameter parameter)
{
if (parameter == null)
{
throw new ArgumentNullException(nameof(parameter));
}
// https://docs.oracle.com/cd/B19306_01/win.102/b14307/OracleDbTypeEnumerationType.htm
if (parameter is OracleParameter)
{
switch (parameter.Value)
{
case OracleBinary oracleBinary:
// returns byte[]
return oracleBinary.Value;
case OracleBoolean oracleBoolean:
// returns bool
return oracleBoolean.Value;
case OracleDate oracleDate:
// returns DateTime
return oracleDate.Value;
case OracleDecimal oracleDecimal:
// oracleDecimal.Value is Decimal, so we convert to correct type.
return parameter.DbType == DbType.Decimal
? oracleDecimal.Value
: Convert.ChangeType(oracleDecimal.Value, parameter.DbType.ToType());
case OracleIntervalDS oracleIntervalDS:
// returns TimeSpan
return oracleIntervalDS.Value;
case OracleIntervalYM oracleIntervalYM:
// returns Long
return oracleIntervalYM.Value;
case OracleTimeStamp oracleTimeStamp:
// returns DateTime
return oracleTimeStamp.Value;
case OracleTimeStampLTZ oracleTimeStampLTZ:
// returns DateTime
return oracleTimeStampLTZ.Value;
case OracleTimeStampTZ oracleTimeStampTZ:
// returns DateTime
return oracleTimeStampTZ.Value;
default:
throw new NotSupportedException(
parameter.Value != null
? parameter.Value.GetType().Name
: parameter.ParameterName);
}
}
else
{
throw new NotSupportedException(parameter.GetType().Name);
}
}
In my case, I'm using Bulk Insert in Oracle, and meet the same error, let me share my solution here. I solved it by adding
oracleCommand.ArrayBindCount = datas.Count;
that is I forgot to set the ArrayBindCount property.
I suggest you convert to String, and after that you convert from String to Integer.
Dim tmpIdSesiónCalificación As String =
parametroIdSesiónCalificación.Value.ToString
_idSesiónCalificación = Convert.ToInt32(tmpIdSesiónCalificación)
I'm getting a parameter and getting a specific product from a stored procedure. This stored procedure is returning many columns (I think around 15-20). Unfortunately, some of these values may be null and this of course produces an error when I try to put them in a variable. Is there a simple way to check and see if these values are NULL so that it doesn't throw an exception or do I need to put an if statement before each assignment? If it helps, here is my code:
public List<Product> ReadSpecificProductDetails(string productAndURLID)
{
ConfigureDataAccess();
myCommand = new SqlCommand("[dbo].[GetSpecificProductDetails]", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
//myCommand.Parameters.Add(productAndURLID);
//myCommand.Parameters.Add(new SqlParameter("#ProductID", SqlDbType.SmallInt));
myCommand.Parameters.AddWithValue("#ProductID", Convert.ToInt16(productAndURLID));
try
{
try
{
myConnection.Open();
myReader = myCommand.ExecuteReader();
}
catch (SqlException exception)
{
exception.Data.Add("cstring", myConfiguration);
throw;
}
catch (InvalidOperationException ex)
{
ex.Data.Add("cStatus", myConnection.State);
throw;
}
//Create a 'Product' list to store the records in
while (myReader.Read())
{
int productID = Convert.ToInt16(myReader["ProductID"]);
string productName = (string)myReader["Name"];
string productNumber = (string)myReader["ProductNumber"];
//int quantitySum = Convert.ToInt16(myReader["QuantitySum"]);
string productColor = (string)myReader["Color"];
int productSafetyStockLevel = Convert.ToInt16(myReader["SafetyStockLevel"]);
int productReorderPoint = Convert.ToInt16(myReader["ReorderPoint"]);
decimal productStandardCost = Convert.ToDecimal(myReader["StandardCost"]);
decimal productListPrice = Convert.ToDecimal(myReader["ListPrice"]);
string productSize = (string)myReader["Size"];
decimal productWeight = Convert.ToDecimal(myReader["Weight"]);
int productDaysToManufacture = Convert.ToInt16(myReader["DaysToManufacture"]);
string productCategoryName = (string)myReader["PC.Name"];
string productSubCategoryName = (string)myReader["PS.Name"];
string productModelName = (string)myReader["PM.Name"];
DateTime productSellStartDate = Convert.ToDateTime(myReader["Sell_Start_Date"]);
DateTime productSellEndDate = Convert.ToDateTime(myReader["Sell_End_Date"]);
DateTime productDiscontinuedDate = Convert.ToDateTime(myReader["Discontinued_Date"]);
Product p = new Product(productID, productName, productNumber, productColor, productSafetyStockLevel, productReorderPoint, productStandardCost,
productListPrice, productSize, productWeight, productDaysToManufacture, productCategoryName, productSubCategoryName, productModelName, productSellStartDate,
productSellEndDate, productDiscontinuedDate);
myProducts.Add(p);
}
}
finally
{
myReader.Close();
myConnection.Close();
}
return myProducts;
}
int? x = dt.Field<int?>( "Field" );
Or
int y = dt.Field<int?>( "Field" ) ?? 0;
C# DBNull and nullable Types - cleanest form of conversion
The top is probably your best approach. You currently have some non nullable types you are populating. So if you want to be able to represent them as null use the top approach. Otherwise you can use the other option to give a default value.
LINQ will be your best friend in these types of situations, as ssg suggested in the comments, however if you want to make a very large addition of null checking, you could implement something like the following:
int productID = (myReader["ProductID"] != null) ? Convert.ToInt16(myReader["ProductID"]) : 0;
or you could simply use an if statement.
Peform a check for DBNULL for the field you may suspect is a null value. In this case all of them.
if (! DBNull.Value.Equals(row[fieldName]))
return (string) row[fieldName] + " ";
else
return String.Empty;
What you can do is create a function that has several overloads for int, string, and DateTime parameters that checks for null
So it would look something like this:
public string CheckNull(string value)
{
if (! DBNull.Value.Equals(value))
return value;
else
return String.Empty;
}
This way you would only have to do something like
object.stringProperty = (string)CheckNull(row["columnName"]);
When using the direct mapping between a data reader and DTO, I use the IsDbNull() method of the data reader. Here are a couple of examples using different data types:
myObj.MyStringProperty = !myReader.IsDBNull("myStringColumn") ? myReader["myStringColumn"].ToString() : null;
myObj.MyNullableDecimalProperty = !myReader.IsDBNull("mydecimalColumn") ? decimal.Parse(myReader["mydecimalColumn"].ToString()) : new decimal?();