I am trying to split a string of values actually individually and trying to send it into database via Store procedure but i can't figure out that how ?
String to be Split: "2013-03-31,1299,2013-03-31,1099,9888, 0"
CODE:
public bool SqlInsert(String parametersString)
{
//It should be split here
SqlConnection sqlCon = new SqlConnection(conStr);
SqlCommand sqlCom = new SqlCommand("AddCoordinates", sqlCon);
sqlCom.CommandType = CommandType.StoredProcedure;
sqlCom.Parameters.Add("#AddedDateTime", SqlDbType.VarChar).Value = "";
sqlCom.Parameters.Add("#IMEI", SqlDbType.VarChar).Value = "";
sqlCom.Parameters.Add("#RecordedDateTime", SqlDbType.VarChar).Value = "";
sqlCom.Parameters.Add("#Latitude", SqlDbType.VarChar).Value = "";
sqlCom.Parameters.Add("#Longitude", SqlDbType.VarChar).Value = "";
sqlCom.Parameters.Add("#IsParking ", SqlDbType.Bit).Value = true;
try
{
sqlCon.Open();
int NoRows = (int)sqlCom.ExecuteNonQuery();
}
catch (Exception ex) { }
finally
{
sqlCon.Close();
}
return true;
}
Looks to me like it's just comma delimited, in which case try:
string[] parts = "2013-03-31,1299,2013-03-31,1099,9888, 0".Split(',');
However, that makes working with parts a bit awkward, so we can go a step further:
string[] fields = new string[] {"date","imei","recorded_date","lat","lon","is_parking"};
List<string,string> dict = Dictionary<string,string>();
for(var i = 0; i < parts.Length; i++) {
var key = fields[i];
var value = parts[i].Trim(); // You may or may not want to trim the value
dict.Add(key,value);
}
You can then pull the individual fields you want and convert them to the type you need, for example:
int imei = int.Parse(dict["imei"]);
Of course, I'm sidestepping a couple of issues like type conversion failure and disparities between parts and fields, but you get the general idea.
The approach mentioned by #Lloyd is the easiest one.Here is the code for your understanding.
string[] parts = "2013-03-31,1299,2013-03-31,1099,9888, 0".Split(',');
sqlCom.Parameters.Add("#AddedDateTime", SqlDbType.VarChar).Value = parts[0].ToString();
sqlCom.Parameters.Add("#IMEI", SqlDbType.VarChar).Value = parts[1].ToString();
sqlCom.Parameters.Add("#RecordedDateTime", SqlDbType.VarChar).Value = Convert.ToDateTime(parts[2].ToString());
sqlCom.Parameters.Add("#Latitude", SqlDbType.VarChar).Value = parts[3].ToString(); ;
sqlCom.Parameters.Add("#Longitude", SqlDbType.VarChar).Value = parts[4].ToString(); ;
sqlCom.Parameters.Add("#IsParking ", SqlDbType.Bit).Value = ((parts[5].ToString().Trim()).Equals("0"))? true: false;
Hope it helps!
Related
I have a method that returns a string from a database based on what i pass to it. The method works but i need to display the result in a textbox on a form. But when i run it the result i keep getting is "System.Collections.Generic.List`1[System.String]". I cant work this out. I try looping through the interest variable with for loop but this doesn't work either.
var interest = GetValue2(tvp, connectionString); -- this is my method that returns a string
textBox2.Text = string.Join(", ", interest.ToString());
this returns "System.Collections.Generic.List`1[System.String]" to textbox2. Any ideas what im missing here? thanks
PART 2:
public static List<String> GetValue2(DataTable tvp, String connectionString)
{
List<String> items = new List<String>();
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("[dbo].[...]", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParameter = new SqlParameter();
tvpParameter.ParameterName = "#..";
tvpParameter.SqlDbType = System.Data.SqlDbType.Structured;
tvpParameter.Value = tvp;
tvpParameter.TypeName = "[dbo].[....]";
cmd.Parameters.Add(tvpParameter);
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Console.WriteLine((String)rdr["id"]);
}
Console.ReadLine();
}
}
return items;
}
Could you share the GetValue2 method? Probably you are calling ToString() on List in that method and it that case the GetValue2 method returns
"System.Collections.Generic.List1[System.String]"
Example:
var test = new List<string>{"some text"};
test.ToString(); // returns System.Collections.Generic.List`1[System.String]
Update:
Because the method GetValue2 returns List<string> avoid calling .ToString() on interest
var interest = GetValue2(tvp, connectionString); // returns List<string>
textBox2.Text = string.Join(", ", interest);
There's also the issue of the List<string> items inside the GetValue2() not being populated.
Here's the corrected method:
public static List<String> GetValue2(DataTable tvp, String connectionString)
{
List<String> items = new List<String>();
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("[dbo].[...]", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParameter = new SqlParameter();
tvpParameter.ParameterName = "#..";
tvpParameter.SqlDbType = System.Data.SqlDbType.Structured;
tvpParameter.Value = tvp;
tvpParameter.TypeName = "[dbo].[....]";
cmd.Parameters.Add(tvpParameter);
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
items.Add((String)rdr["id"]);
}
}
}
return items;
}
I have a text file contains around 8000 lines.
Each lines must have 90 characters.
Each lines contain different blocks so I have to use substring for each blocks.
For Eg.
xx-xxxxxxxxx-xx-xxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxx
I use Substring(x,x) to get each block in for loop.
Some of lines have do not have 122 characters,
For Eg. xx-xxxxxxxxx-xx-xxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxx-xxxxx
so i would like to skip those lines and proceed for others. I don't understand the proper use of String.Skip function in C#.
Here is my code.
public void getext()
{
// bool check = false;
MySqlConnectionStringBuilder con = new MySqlConnectionStringBuilder();
con.Server = "xxx";
con.UserID = "xxx";
con.Password = "xxx";
con.Database = "xxx";
MySqlConnection sqlcon = new MySqlConnection(con.ToString());
string padding = "";
try
{
sqlcon.Open();
//var watch = System.Diagnostics.Stopwatch.StartNew();
var path = "C:\\xxx\\xxx\\xxx\\1.txt";
var lines = File.ReadAllLines(path);
for (var i = 0; i < lines.Length; i += 1)
{
string str = lines[i].ToString();
string code, control1, actype, control2, filler, control3, sponsor,
control4, amtdate, control5;
code = str.Substring(0, 2);
control1 = str.Substring(2, 9);
actype = str.Substring(11, 2);
control2 = str.Substring(13, 18);
filler = str.Substring(31, 40);
control3 = str.Substring(74, 16);
sponsor = str.Substring(90, 20);
MySqlCommand cmd = new MySqlCommand("addext", sqlcon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("code", MySqlDbType.VarChar).Value = code;
cmd.Parameters.Add("control1", MySqlDbType.VarChar).Value = control1;
cmd.Parameters.Add("actype", MySqlDbType.VarChar).Value = actype;
cmd.Parameters.Add("control2", MySqlDbType.VarChar).Value = control2;
cmd.Parameters.Add("filler", MySqlDbType.VarChar).Value = filler;
cmd.Parameters.Add("control3", MySqlDbType.VarChar).Value = control3;
cmd.Parameters.Add("sponsor", MySqlDbType.VarChar).Value = sponsor;
cmd.ExecuteNonQuery();
//sqlcon.Close();
label1.Visible = true;
//sqlcon.Close();
//watch.Stop();
//var elapsedMs = watch.Elapsed.TotalMinutes;
label1.Text = "success";
// sqlcon.Close();
}
sqlcon.Close();
}
catch (Exception ex)
{
label1.Visible = true;
label1.Text = "fail" + ex.ToString();
}
}
If you want to skip a number/line within your loop you can use
continue;
example:
for (var i = 0; i < lines.Length; i += 1)
{
string str = lines[i];
if (str.length != 122) // We only want to Work with lines which are 122 chars long.
continue;
DoWork(); // Insert you code here ;)
}
I believe you want to skip lines which are less than 122 characters? You can filter them out from your loop and process only the ones that have required length.
foreach(var str in lines.Where(x=>x.Length>=122))
{
string code, control1, actype, control2, filler, control3, sponsor,
control4, amtdate, control5;
code = str.Substring(0, 2);
// rest of your code
}
The Filter and Foreach approach would keep away the indices, increasing readability of the code
I'm new to C#, and write this code for calling a SQL Server stored procedure:
using (SqlConnection con = new SqlConnection(Connection))
{
using (SqlCommand cmd = new SqlCommand("CheckValidbehzad", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p_bank", SqlDbType.VarChar).Value = p_bank;
cmd.Parameters.Add("#p_pay_date", SqlDbType.VarChar).Value = p_pay_date;
cmd.Parameters.Add("#p_bill_id", SqlDbType.VarChar).Value = p_bill_id;
cmd.Parameters.Add("#p_payment_id", SqlDbType.VarChar).Value = p_payment;
cmd.Parameters.Add("#p_ref_code", SqlDbType.VarChar).Value = p_ref_code;
cmd.Parameters.Add("#p_branch", SqlDbType.VarChar).Value = p_branch;
cmd.Parameters.Add("#p_channel_type", SqlDbType.VarChar).Value = p_channel;
cmd.Parameters.Add("#p_send_date", SqlDbType.VarChar).Value = p_send_date;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
//TempCode = reader["PaymentID"].ToString();
}
}
}
That stored procedure sometimes return ErrorNumber in result and sometimes it returns PaymentID. How can I check this scenario?
if( reader has ErrorNumber field) then
do something
else
do something else
Thanks all.
Not sure how exactly you can distinguish these two columns returned - if the column is present or missing (depending on the situation), then you can check for the presence of the column:
while (reader.Read())
{
try
{
int paymenIdPos = reader.GetOrdinal("PaymentID");
// if found --> read payment id
int paymentID = reader.GetInt32(paymenIdPos);
}
catch(IndexOutOfRangeException)
{
// if "PaymentID" is not found --> read the "ERrorNumber"
int errorCode = reader.GetInt32("ErrorNumber");
}
}
you can check with GetOrdinal, as marc_s suggested, or like this:
if (reader.GetSchemaTable().Select("ColumnName = 'PaymentId'").Length > 0)
{
//do something here with pamynet
}
else if (reader.GetSchemaTable().Select("ColumnName = 'ErrorNumber'").Length > 0)
{
//do your stuff here with error number
}
The situation is following, i have a stored procedure in SQL Server , this has a few output parameters, one of them is a bit type, what I want is to take the value of that parameter, but I have a conversion error, InvalidCastException.
This is my code:
public void exec()
{
String strConnString = "Server=.\\SQLEXPRESS;Database=recalls;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "findVinCamp";
int c = Int32.Parse(campaing.Text);
cmd.Parameters.Add("#camp", SqlDbType.Int).Value = c;
cmd.Parameters.Add("#vin", SqlDbType.VarChar, 100).Value = vin.Text;
cmd.Parameters.Add("#desc", SqlDbType.NVarChar, 255).Direction = ParameterDirection.Output;
cmd.Parameters.Add("#st", SqlDbType.VarChar, 50).Direction = ParameterDirection.Output;
cmd.Parameters.Add("#bit", SqlDbType.Bit).Direction = ParameterDirection.Output;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
bit = (int)cmd.Parameters["#bit"].Value; //Exception Here
if (bit == 1)
{
desc.Text = cmd.Parameters["#desc"].Value.ToString();
stt.Text = cmd.Parameters["#st"].Value.ToString();
camp = cmd.Parameters["#camp"].Value.ToString();
if (stt.Text.Equals("APPLIED"))
{
stt.ForeColor = System.Drawing.Color.LawnGreen;
}
else
{
stt.ForeColor = System.Drawing.Color.Firebrick;
label3.Enabled = true;
newstatus.Enabled = true;
update.Enabled = true;
}
}
else
{
MessageBox.Show("Doesn't exits!");
}
}
I'm trying to assign the bit parameter to a int variable. Any question post on comments.
I change the (int) to this, now works perfectly:
Boolean lol = Convert.ToBoolean(cmd.Parameters["#bit"].Value);
Use this following Line
bool isConfirmed = (bool)cmd.Parameters["#bit"].Value;
if(isConfirmed ){
desc.Text = cmd.Parameters["#desc"].Value.ToString();
stt.Text = cmd.Parameters["#st"].Value.ToString();
camp = cmd.Parameters["#camp"].Value.ToString();
if (stt.Text.Equals("APPLIED"))
{
stt.ForeColor = System.Drawing.Color.LawnGreen;
}
else
{
stt.ForeColor = System.Drawing.Color.Firebrick;
label3.Enabled = true;
newstatus.Enabled = true;
update.Enabled = true;
}
}
else{
MessageBox.Show("Doesn't exits!");
}
**UPDATE: **if the bit column allows nulls -- many ways you can do this
bool isConfirmed = cmd.Parameters["#bit"].Value as bool? ?? null;
and also read this- SQL Server Data Types and Their .NET Framework Equivalents
I believe a bit will convert to a boolean. Which should make your code a bit simpler too.
i.e.
...
var bit = (bool)cmd.Parameters["#bit"].Value;
if (bit)
{
...
You are trying to convert your boolean output to INT, please convert it in Boolean:
bool bitValue= Convert.ToBoolean(cmd.Parameters["#bit"].Value)
I have a gridview and I want to checked line in insert but I see this error:
CommandText property has not been initialized.
I guess my mistake about strArrays. I'm working two days about it
How can I fixed?
StringBuilder stringBuilder = new StringBuilder(string.Empty);
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString.ToString());
SqlCommand sqlCommand = new SqlCommand();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
int type = 2;
CheckBox chkUpdate = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chkSelect");
TextBox txtAmount = (TextBox)GridView1.Rows[i].Cells[5].FindControl("txtAmount");
if (chkUpdate != null)
{
if (chkUpdate.Checked)
{
string strID = GridView1.Rows[i].Cells[1].Text;
GridView1.Rows[i].FindControl("txtLocation")).Text;
string text = this.GridView1.Rows[i].Cells[1].Text;
string[] strArrays = new string[] { "INSERT INTO [OrderCancel]
([OrderID],
[Message],
[Type],
[RelationProductID],
[Amount])
VALUES(" ,
Request.QueryString["o"] ,
",'" , txtWhy.Text ,
"',",type.ToString(),",
" , strID , "," ,
txtAmount.Text , ");" };
stringBuilder.Append(string.Concat(strArrays));
//append update statement in stringBuilder
stringBuilder.Append(string.Concat(strArrays));
}
}
try
{
try
{
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = stringBuilder.ToString();
sqlCommand.Connection = sqlConnection;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
}
catch (SqlException sqlException)
{
throw new Exception(string.Concat("Error in Updation",
sqlException.Message));
}
}
finally
{
sqlConnection.Close();
}
Your code could be cleaned up, you could do the following:
private readonly string dbConnection = "...";
private const string query = "... Column = #Column";
For the sake of brevity I've added ... which will correlate to your Connection String and your query with parameters.
var message = String.Empty;
using(var connection = new SqlConnection(dbConnection))
using(var command = new SqlCommand(query, dbConnection))
{
connection.Open();
command.CommandType = CommandType.Text;
command.Parameters.Add("#Column", SqlDbType.NVarChar).Value = message;
command.ExecuteNonQuery();
}
So that small snippet would be inside of a method, which would pass a model of the data in your Grid. Then when you pass a value from your Grid, then you would build your model and pass to the method which will write to your database.
Also, when you use a StringBuilder you will also need to call ToString(); to ensure that it is a string rather than a StringBuilder when your utilizing.
This error usually happens if you do not set the commandText property. looking at your code it looks like your stringbuilder variable is not getting set. have you tried putting a breakpoint inside your "chkUpdate.Checked" loop? if yes, can you post the sql that gets constructed in your loop