My query will execute the first time in a switch case loop, but during the second case nothing happens with it
everything is written inside of a for loop, it manages to add the first query into the database properly but after that it doesn't
string sQuery = string.Format("'{0}','{1}','{2}','{3}','{4}','{5}','{6}',{7},'{8}','{9}',{10}", sName, sMiddleName, sSurname, sBirthdate, sSex, sNationality, sDateOfArrival, sCardID, sUsername, sPassword, sPhoneNumber);
SqlConnection cnn;
cnn = new SqlConnection(Globals.sqlConnect);
cnn.Open();
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "";
for (int i = 0; i < 2; i++)
{
switch (i)
{
case 0:
sql = "INSERT INTO dbo.Refugee ([Name],[Middlename],[Surname],[Birthdate],[Sex],[Nationality],[Date_of_arrival],[ID_Card_Number],[Username],[Password],[Phone_Number]) VALUES(" + sQuery + ")";
command = new SqlCommand(sql, cnn);
adapter.InsertCommand = command;
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
break;
case 1:
if (Properties.Settings.Default.HoF == true)
{
sQuery = string.Format("'{0}' ,{1}",Properties.Settings.Default.Familyname,tb_cardID);
sql = "INSERT INTO dbo.Family ([Family_name],[Head_Of_Family_ID_Card_Number]) VALUES ("+ sQuery +")";
command = new SqlCommand(sql, cnn);
adapter.InsertCommand = command;
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
}
break;
Since I didn't know where the values for the parameters came from I just assumed they were passed into the procedure. You need to check the datatypes of the of the parameters in your database and change the code accordingly. Convert the values to matching types. using blocks ensure that your database objects are closed and disposed even if there is an error. Using parameters protects you form Sql injection.
The loop ,switch and dataadapter are unnecessary.
private void OPCode(string sName,string sMiddleName,string sSurname,DateTime sBirthdate,string sSex,string sNationality,DateTime sDateOfArrival,int sCardID,string sUsername,string sPassword,string sPhoneNumber, int tb_cardID)
{
using (SqlConnection cnn = new SqlConnection(Globals.sqlConnect))
{
using (SqlCommand command = new SqlCommand("INSERT INTO dbo.Refugee ([Name],[Middlename],[Surname],[Birthdate],[Sex],[Nationality],[Date_of_arrival],[ID_Card_Number],[Username],[Password],[Phone_Number]) VALUES (#sName, #sMiddleName, #sSurname, #sBirthdate, #sSex, #sNationality, #sDateOfArrival, #sCardID, #sUsername, #sPassword, #sPhoneNumber);", cnn))
{
command.Parameters.Add("#sName", SqlDbType.VarChar).Value = sName;
command.Parameters.Add("#sMiddleName", SqlDbType.VarChar).Value = sMiddleName;
command.Parameters.Add("#sSurname", SqlDbType.VarChar).Value = sSurname;
command.Parameters.Add("#sBirthdate", SqlDbType.DateTime).Value = sBirthdate;
command.Parameters.Add("#sSex", SqlDbType.VarChar).Value = sSex;
command.Parameters.Add("#sNationality", SqlDbType.VarChar).Value = sNationality;
command.Parameters.Add("#sDateOfArrival", SqlDbType.DateTime).Value = sDateOfArrival;
command.Parameters.Add("#sCardID", SqlDbType.Int).Value = sCardID;
command.Parameters.Add("#sUsername", SqlDbType.VarChar).Value = sUsername;
command.Parameters.Add("#sPassword", SqlDbType.VarChar).Value = sPassword;
command.Parameters.Add("#sPhoneNumber", SqlDbType.VarChar).Value = sPhoneNumber;
cnn.Open();
command.ExecuteNonQuery();
} //disposes command
if (Properties.Settings.Default.HoF == true)
{
using(SqlCommand command = new SqlCommand("INSERT INTO dbo.Family ([Family_name],[Head_Of_Family_ID_Card_Number]) VALUES (#FamilyName, #tb_carID;", cnn))
{
command.Parameters.Add("#Familyname", SqlDbType.VarChar).Value = Properties.Settings.Default.Familyname;
command.Parameters.Add("#tb_cardID", SqlDbType.Int).Value = tb_cardID;
command.ExecuteNonQuery();
}//disposes second command
}
}//closes and disposes connection
}
Related
This question already has answers here:
Fetch scope_identity value in C# code from stored procedure in 3 tier architecture
(2 answers)
Closed 4 years ago.
I have a stored procedure that will return the SCOPE_IDENTITY() which is the ID for the row just added.
I have run the procedure from my C# application and adds the correct data to the database. What I need is for this returned value to be stored as a string in C~ so I can populate a text box in the UI.
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlDataAdapter aa = new SqlDataAdapter("sp_insert_order", con);
aa.SelectCommand.CommandType = CommandType.StoredProcedure;
aa.SelectCommand.Parameters.Add("#customer_id", SqlDbType.VarChar, (50)).Value = comboBox1.SelectedItem;
aa.SelectCommand.ExecuteNonQuery();
con.Close();
Changed to
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlDataAdapter aa = new SqlDataAdapter("sp_insert_order", con);
aa.SelectCommand.CommandType = CommandType.StoredProcedure;
aa.SelectCommand.Parameters.Add("#customer_id", SqlDbType.VarChar, (50)).Value = comboBox1.SelectedItem;
object oString = aa.SelectCommand.ExecuteScalar();
string myString = "";
if (oString != null)
{
myString = oString.ToString();
textBox1.Text = myString;
}
Textbox1 is still blank. :(
Ok, we're assuming your SProc is returning properly. Try assigning an output parameter as follows:
SqlConnection cnx = new SqlConnection(WebConfigurationManager.ConnectionStrings["yourConnName"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnx;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "testSProc";
cmd.Parameters.AddWithValue("name", "test Name");
SqlParameter outputParam = cmd.Parameters.Add("outID", SqlDbType.Int);
outputParam.Direction = ParameterDirection.Output;
object oString;
cnx.Open();
cmd.ExecuteNonQuery();
cnx.Close();
TextBox1.Text = outputParam.Value.ToString();
This question already has answers here:
How to execute a stored procedure within C# program
(14 answers)
Closed 4 years ago.
I am Getting the error while executing the code, CommandText Property has been not initialized
public DataTable Mappingdataload(string name)
{
try
{
string spname = "";
switch (name.ToLower())
{
case "student":
spname = "RetrieveStudent";
break;
case "organization":
spname = "RetrieveOrganization";
break;
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = SQLConClass.GetSQLConnection();
cmd.CommandText = spname;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);
DataTable dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
return dataTable;
}
catch (Exception)
{
throw;
}
}
you are getting this error because command text is not initialized :)
It is always better to first make connection and then create command. check the code below.
var conn = SQLConClass.GetSQLConnection();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = spname;
cmd.CommandType = CommandType.StoredProcedure;
also better to use it like this:
using (var conn = SQLConClass.GetSQLConnection())
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = spname;
cmd.CommandType = CommandType.StoredProcedure;
using (var reader = cmd.ExecuteReader())
{
....
}
}
I am attempting to create a simple news and image system, I first need to use SCOPE_IDENTITY() and execute scalar, but I'm not having much luck. I get a:
The name 'newID' does not exist in the current context
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("/images/admin/news/" + FileName));
//Add Entry to DataBase
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
int newID = 0;
string strQuery = #"insert into tblFiles (FileName, FilePath) values(#FileName, #FilePath); select cast(scope_identity() As int);";
using (SqlConnection connection = new SqlConnection(strConnString))
using (SqlCommand command = new SqlCommand(strQuery, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#FileName", SqlDbType.VarChar).Value = FileName;
command.Parameters.Add("#FilePath", SqlDbType.VarChar).Value = "/images/admin/news/" + FileName;
try
{
connection.Open();
newID = (int)command.ExecuteScalar();
}
catch
{
}
}
}
if (newID > 0)
{
string strAddNewsQuery = #"insert into tblNews (newsTitle, newsDate, newsSummary, newsContent, newsPicID)
values(#newsTitle, #newsDate, #newsSummary, #newsContent, #newsPicID)";
using (SqlConnection connection = new SqlConnection(strConnString))
using (SqlCommand command = new SqlCommand(strAddNewsQuery, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#newsTitle", SqlDbType.VarChar).Value = FileName;
command.Parameters.AddWithValue("#newsDate", txtnewsdate.Text);
command.Parameters.AddWithValue("#newsSummary", txtnewssummary.Text);
command.Parameters.AddWithValue("#newsContent", txtnewsmaincontent.Text);
command.Parameters.Add("#newsPicID", SqlDbType.Int).Value = newID;
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch
{
}
finally {
connection.Close();
connection.Dispose();
}
}
}
}
}
An int does not have properties you can access. Change
command.Parameters.AddWithValue("#newsPicID", newID.Value);
into
command.Parameters.AddWithValue("#newsPicID", newID);
Even better is to use parameters with the database value type specified.
command.Parameters.Add("#newsPicID", SqlDbType.Int).Value = newID;
But you are trying to get the SCOPE_IDENTITY() of table tblNews, not from tblFiles to be used in tblNews as newsPicID. You need to get SCOPE_IDENTITY() from the first database command.
UPDATE
And you need to assign the connection to the command.
SqlCommand cmd = new SqlCommand(strQuery, con)
UPDATE 2
Here is a complete snippet to get you started. Notice the wrapping with using. This ensures proper disposal of connections.
int newID = 0;
using (SqlConnection connection = new SqlConnection(strConnString))
using (SqlCommand command = new SqlCommand(strQuery, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#FileName", SqlDbType.VarChar).Value = FileName;
command.Parameters.Add("#FilePath", SqlDbType.VarChar).Value = "/images/admin/news/" + FileName;
try
{
connection.Open();
newID = (int)command.ExecuteScalar();
}
catch
{
}
}
if (newID > 0)
{
using (SqlConnection connection = new SqlConnection(strConnString))
using (SqlCommand command = new SqlCommand(strAddNewsQuery, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#newsTitle", SqlDbType.VarChar).Value = FileName;
//etc
command.Parameters.Add("#newsPicID", SqlDbType.Int).Value = newID;
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch
{
}
}
}
I have two table.I need to get calorificValue from the food table and daily_gained from the calorie_tracker table to then make some calculations.I've written this code, I know it not efficent. It retrieves daily_gained but failed to get calorificValue.
MySqlCommand cmd = new MySqlCommand("SELECT name,calorificValue FROM myfitsecret.food where name=#name", cnn);
MySqlCommand cmd2 = new MySqlCommand("SELECT sportsman_id,daily_gained FROM myfitsecret.calorie_tracker where sportsman_id=#sportsman_id", cnn);
cmd2.Parameters.AddWithValue("#sportsman_id", Login.userID);
string s = (comboBox1.SelectedItem).ToString();
cmd.Parameters.AddWithValue("#name",s);
cmd2.Connection.Open();
MySqlDataReader rd = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
int burned = 0;
if (rd.HasRows) // if entered username and password have the data
{
while (rd.Read()) // while the reader can read
{
if (rd["sportsman_id"].ToString() == Login.userID) // True for admin
{
burned += int.Parse(rd["daily_gained"].ToString());
}
}
}
cmd2.Connection.Close();
cmd.Connection.Open();
MySqlDataReader rd2 = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (rd2.HasRows) // if entered username and password have data
{
while (rd2.Read()) // while the reader can read
{
if (rd2["name"].ToString() == s)
{
burned += int.Parse(rd2["calorificValue"].ToString());
}
}
}
MessageBox.Show(burned+"");
DataTable tablo = new DataTable();
string showTable = "SELECT * from myfitsecret.calorie_tracker where sportsman_id=#sportsman_id";
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand showCommand = new MySqlCommand();
showCommand.Connection = cnn;
showCommand.CommandText = showTable;
showCommand.CommandType = CommandType.Text;
showCommand.Parameters.AddWithValue("#sportsman_id", Login.userID);
adapter.SelectCommand = showCommand;
adapter.Fill(tablo);
dataGridView1.DataSource = tablo;
cnn.Close();
Why don't you just use the scalar function SUM and let the database do its job instead of writing a lot of code?
int burned = 0;
string s = comboBox1.SelectedItem.ToString();
cnn.Open();
string cmdText = #"SELECT SUM(calorificValue)
FROM myfitsecret.food
WHERE name=#name";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = s;
object result = cmd.ExecuteScalar();
burned += (result != null ? Convert.ToInt32(result) : 0);
}
cmdText = #"SELECT SUM(daily_gained)
FROM myfitsecret.calorie_tracker
WHERE sportsman_id=#sportsman_id";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
cmd.Parameters.Add("#sportsman_id", MySqlDbType.Int32).Value = Login.userID;
object result = cmd.ExecuteScalar();
burned += (result != null ? Convert.ToInt32(result) : 0);
}
Not visible from your code, but also the connection should be created inside a using statement (very important with MySql that is very restrictive with simultaneous open connections)
We could also use a different approach putting the two commands together and separating them with a semicolon. This is called batch commands and they are both executed with just one trip to the database. Of course we need to fallback using the MySqlDataReader to get the two results passing from the first one to the second one using the NextResult() method (see here MSDN for Sql Server)
string cmdText = #"SELECT SUM(calorificValue)
FROM myfitsecret.food
WHERE name=#name;
SELECT SUM(daily_gained)
FROM myfitsecret.calorie_tracker
WHERE sportsman_id=#sportsman_id";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
// Add both parameters to the same command
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = s;
cmd.Parameters.Add("#sportsman_id", MySqlDbType.Int32).Value = Login.userID;
cnn.Open();
using(MySqlDataReader reader = cmd.ExecuteReader())
{
// get sum from the first result
if(reader.Read()) burned += Convert.ToInt32(reader[0]);
// if there is a second resultset, go there
if(reader.NextResult())
if(reader.Read())
burned += Convert.ToInt32(reader[0]);
}
}
Your issues could be around closing a connection and then trying to open it again. Either way it's fairly inefficient to be closing and opening connections.
MySqlCommand cmd = new MySqlCommand("SELECT name,calorificValue FROM myfitsecret.food where name=#name", cnn);
string s = (comboBox1.SelectedItem).ToString();
cmd.Parameters.AddWithValue("#name",s);
MySqlCommand cmd2 = new MySqlCommand("SELECT SUM(daily_gained) FROM myfitsecret.calorie_tracker where sportsman_id=#sportsman_id", cnn);
cmd2.Parameters.AddWithValue("#sportsman_id", Login.userID);
cnn.Open();
MySqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows) // if entered username and password have data
{
while (rd.Read()) // while the reader can read
{
burned += int.Parse(rd["calorificValue"].ToString());
}
}
burned = cmd2.ExecuteScalar();
MessageBox.Show(burned+"");
cnn.Close();
I wrote some code that takes some values from one table and inserts the other table with these values.(not just these values, but also these values(this values=values from the based on table))
and I get this error:
System.Data.OleDb.OleDbException (0x80040E10): value wan't given for one or more of the required parameters.`
here's the code. I don't know what i've missed.
string selectedItem = comboBox1.SelectedItem.ToString();
Codons cdn = new Codons(selectedItem);
string codon1;
int index;
if (this.i != this.counter)
{
//take from the DataBase the matching codonsCodon1 to codonsFullName
codon1 = cdn.GetCodon1();
//take the serialnumber of the last protein
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
string last= "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
dr.Read();
index = dr.GetInt32(0);
//add the amino acid to tblOrderAA
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
string insertCommand = "INSERT INTO tblOrderAA(orderAASerialPro, orderAACodon1) "
+ " values (?, ?)";
using (OleDbCommand command = new OleDbCommand(insertCommand, connection))
{
connection.Open();
command.Parameters.AddWithValue("orderAASerialPro", index);
command.Parameters.AddWithValue("orderAACodon1", codon1);
command.ExecuteNonQuery();
}
}
}
EDIT:I put a messagebox after that line:
index = dr.GetInt32(0);
to see where is the problem, and I get the error before that. I don't see the messagebox
Your SELECT Command has a syntax error in it because you didn't enclose it with quotes.
Change this:
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
to
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = ?";
OleDbCommand getSerial = new OleDbCommand(last, conn);
getSerial.Parameters.AddWithValue("?", this.name);
OleDbDataReader dr = getSerial.ExecuteReader();
This code is example from here:
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Try to do the same as in the example.