Related
How can I put these queries in a loop (from student_fee_record_2 to student_fee_record_10) There is only difference between student_fee_record_1 and others, from student_fee_record_2 to 10 have no insertion for fee_txt. I need them to insert in a loop separately from student_fee_record_1, So that my code can be shorter, these are too much lines of code, Please help me to short this code using loop. And please note that I’m using varchar() for all fields in my database.
Here is my code.
private void btn_add_Click(object sender, EventArgs e)
{
string constring = "Data Source=Niazi;Initial Catalog=IIHS;Integrated Security=True";
SqlConnection conDataBase = new SqlConnection(constring);
conDataBase.Open();
string Query = "insert into student_fee_record_1 (student_id, student_name, student_f_name," +
"program, address, email_address, date, fee_submit)" +
"values('" + std_id_txt.Text + "','" + std_name_txt.Text + "','" + f_name_txt.Text + "'," +
"'" + program_txt.Text + "', '" + address_txt.Text + "', '" + email_txt.Text + "'," +
"'" + date_txt.Text + "', '" + fee_txt.Text + "');"+
"insert into student_fee_record_2 (student_id, student_name, student_f_name," +
"program, address, email_address, date)"+
"values('" + std_id_txt.Text + "', '" + std_name_txt.Text + "', '" + f_name_txt.Text + "', " +
"'" + program_txt.Text + "', '" + address_txt.Text + "', '" + email_txt.Text + "'," +
"'" + date_txt.Text + "')" +
"insert into student_fee_record_3 (student_id, student_name, student_f_name," +
"program, address, email_address, date)" +
"values('" + std_id_txt.Text + "', '" + std_name_txt.Text + "', '" + f_name_txt.Text + "', " +
"'" + program_txt.Text + "', '" + address_txt.Text + "', '" + email_txt.Text + "'," +
"'" + date_txt.Text + "')" +
"insert into student_fee_record_4 (student_id, student_name, student_f_name," +
"program, address, email_address, date)" +
"values('" + std_id_txt.Text + "', '" + std_name_txt.Text + "', '" + f_name_txt.Text + "', " +
"'" + program_txt.Text + "', '" + address_txt.Text + "', '" + email_txt.Text + "'," +
"'" + date_txt.Text + "')" +
"insert into student_fee_record_5 (student_id, student_name, student_f_name," +
"program, address, email_address, date)" +
"values('" + std_id_txt.Text + "', '" + std_name_txt.Text + "', '" + f_name_txt.Text + "', " +
"'" + program_txt.Text + "', '" + address_txt.Text + "', '" + email_txt.Text + "'," +
"'" + date_txt.Text + "')" +
"insert into student_fee_record_6 (student_id, student_name, student_f_name," +
"program, address, email_address, date)" +
"values('" + std_id_txt.Text + "', '" + std_name_txt.Text + "', '" + f_name_txt.Text + "', " +
"'" + program_txt.Text + "', '" + address_txt.Text + "', '" + email_txt.Text + "'," +
"'" + date_txt.Text + "')" +
"insert into student_fee_record_7 (student_id, student_name, student_f_name," +
"program, address, email_address, date)" +
"values('" + std_id_txt.Text + "', '" + std_name_txt.Text + "', '" + f_name_txt.Text + "', " +
"'" + program_txt.Text + "', '" + address_txt.Text + "', '" + email_txt.Text + "'," +
"'" + date_txt.Text + "')" +
"insert into student_fee_record_8 (student_id, student_name, student_f_name," +
"program, address, email_address, date)" +
"values('" + std_id_txt.Text + "', '" + std_name_txt.Text + "', '" + f_name_txt.Text + "', " +
"'" + program_txt.Text + "', '" + address_txt.Text + "', '" + email_txt.Text + "'," +
"'" + date_txt.Text + "')" +
"insert into student_fee_record_9 (student_id, student_name, student_f_name," +
"program, address, email_address, date)" +
"values('" + std_id_txt.Text + "', '" + std_name_txt.Text + "', '" + f_name_txt.Text + "', " +
"'" + program_txt.Text + "', '" + address_txt.Text + "', '" + email_txt.Text + "'," +
"'" + date_txt.Text + "')" +
"insert into student_fee_record_10 (student_id, student_name, student_f_name," +
"program, address, email_address, date)" +
"values('" + std_id_txt.Text + "', '" + std_name_txt.Text + "', '" + f_name_txt.Text + "', " +
"'" + program_txt.Text + "', '" + address_txt.Text + "', '" + email_txt.Text + "'," +
"'" + date_txt.Text + "')";
//SqlConnection conDataBase = new SqlConnection(constring);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
//conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Record added successfully.");
ClearAll(this);
load_table();
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Easy
private void btn_add_Click(object sender, EventArgs e)
{
string constring = "Data Source=Niazi;Initial Catalog=IIHS;Integrated Security=True";
SqlConnection conDataBase = new SqlConnection(constring);
conDataBase.Open();
string Query = "";
for (int recordNum = 1; recordNum <= 10; recordNum++)
{
if (recordNum == 1)
{
Query = string.Format(
"insert into student_fee_record_{0} (student_id, student_name, student_f_name," +
"program, address, email_address, date, fee_submit)" +
"values('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')",
recordNum.ToString(), std_id_txt.Text, std_name_txt, f_name_txt.Text, program_txt.Text, address_txt.Text, date_txt.Text, email_txt.Text, fee_txt.Text);
}
else
{
Query = string.Format(
"insert into student_fee_record_{0} (student_id, student_name, student_f_name," +
"program, address, email_address, date)" +
"values('{1}','{2}','{3}','{4}','{5}','{6}','{7}')",
recordNum.ToString(), std_id_txt.Text, std_name_txt, f_name_txt.Text, program_txt.Text, address_txt.Text, date_txt.Text, email_txt.Text);
}
//SqlConnection conDataBase = new SqlConnection(constring);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
//conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Record added successfully.");
ClearAll(this);
load_table();
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
here's my code,what i have to do that my code stops read data when files data ended.
string path = string.Concat(Server.MapPath("~/TempFiles/"), Fileupload1.FileName);
string text = System.IO.File.ReadAllText(path);
string[] lines = text.Split('\n');
con.Open();
SqlCommand cmd = new SqlCommand();
string[] Values;
foreach (string line1 in lines)
{
int a = 0;
Values = line1.Split(';');
a = a + 1;
// string query = "INSERT INTO cdr_info VALUES ('" + Values[0] + "'," + Values[1] + ",'" + Values[2] + "','" + Values[3] + "'," +
string query = "INSERT INTO cdr_info VALUES( '" + Values[0] + "', '" + Values[1] + "', '" + Values[2] + "', '" + Values[3] + "', '" + Values[4] + "', '" + Values[5] + "', '" + Values[6] + "', '" + Values[7] + "', '" + Values[8] + "', '" + Values[9] + "'," +
" '" + Values[10] + "', '" + Values[11] + "', '" + Values[12] + "', '" + Values[13] + "', '" + Values[14] + "','" + Values[15] + "', '" + Values[16] + "', '" + Values[17] + "', '" + Values[18] + "','" + Values[19] + "'," +
"'" + Values[20] + "','" + Values[21] + "', '" + Values[22] + "', '" + Values[23] + "', '" + Values[24] + "', '" + Values[25] + "','" + Values[26] + "', '" + Values[27] + "', '" + Values[28] + "', '" + Values[29] + "', " +
" '" + Values[30] + "', '" + Values[31] + "', '" + Values[32] + "', '" + Values[33] + "', '" + Values[34] + "'," +
"'" + Values[35] + "', '" + Values[36] + "', '" + Values[37] + "', '" + Values[38] + "','" + Values[39] + "', '" + Values[40] + "', '" + Values[41] + "', '" + Values[42] + "'," +
"'" + Values[43] + "', '" + Values[44] + "', '" + Values[45] + "', '" + Values[46] + "', '" + Values[47] + "', '" + Values[48] + "', '" + Values[49] + "','" + Values[50] + "', '" + Values[51] + "'," +
" '" + Values[52] + "', '" + Values[53] + "', '" + Values[54] + "', '" + Values[55] + "', '" + Values[56] + "','" + Values[57] + "', '" + Values[58] + "', '" + Values[59] + "', '" + Values[60] + "', '" + Values[61] + "'," +
"'" + Values[62] + "', '" + Values[63] + "', '" + Values[64] + "', '" + Values[65] + "', '" + Values[66] + "','" + Values[67] + "','" + Values[68] + "','" + Values[69] + "', '" + Values[70] + "'," +
"'" + Values[71] + "', '" + Values[72] + "','" + Values[73] + "','" + Values[74] + "', '" + Values[75] + "', '" + Values[76] + "', '" + Values[77] + "', '" + Values[78] + "', '" + Values[79] + "', '" + Values[80] + "'," +
" '" + Values[81] + "', '" + Values[82] + "', '" + Values[83] + "', '" + Values[84] + "', '" + Values[85] + "','" + Values[86] + "', '" + Values[87] + "','" + Values[88] + "', '" + Values[89] + "', '" + Values[90] + "'," +
" '" + Values[91] + "', '" + Values[92] + "', '" + Values[93] + "', '" + Values[94] + "', '" + Values[95] + "', '" + Values[96] + "', '" + Values[97] + "', '" + Values[98] + "', '" + Values[99] + "', '" + Values[100] + "'," +
" '" + Values[101] + "', '" + Values[102] + "', '" + Values[103] + "'," +
" '" + Values[104] + "', '" + Values[105] + "', '" + Values[106] + "', '" + Values[107] + "', '" + Values[108] + "')";
// string query = "INSERT INTO demooo VALUES ('" + Values[0] + "','" + Values[1] + "','" + Values[2] + "')";
cmd = new SqlCommand(query,con);
cmd.ExecuteNonQuery();
}
you will get exception splitted items not having expected item count. you can add validation to avoid the exception like below
Values = line1.Split(';');
int itemcount = 108;
if(line1.Length >= itemcount)
{
// your insert code
}
How can I open a data reader after closing it? I'm using Visual Studio 2010.
Here is my code.
bool result = Directory.EnumerateFiles(#"C:\Users\Moon\Documents\Visual Studio 2010\Projects\cdrInsertion\cdrInsertion\TempFiles").Any();
if (!result)
{
Response.Write("Folder is empty");
}
else
{
DirectoryInfo info = new DirectoryInfo(#"C:\Users\Moon\Documents\Visual Studio 2010\Projects\cdrInsertion\cdrInsertion\TempFiles");
FileInfo[] files = info.GetFiles();
SqlConnection con = new SqlConnection("Data Source = MOON-PC\\SQLEXPRESS; Initial Catalog = Call_Detail_Record; Integrated Security = true; Persist Security Info=False;");
con.Open();
SqlCommand cmd = new SqlCommand();
SqlDataReader readr = null;
foreach (FileInfo file in files)
{
string path = #"C:\Users\Moon\Documents\Visual Studio 2010\Projects\cdrInsertion\cdrInsertion\TempFiles\"+ file;
string queryfile = "select * from file_log";
cmd = new SqlCommand(queryfile,con);
readr = cmd.ExecuteReader();
while (readr.Read())
{
(readr.Open();)<----here i want to open it.
string filnames = readr["file-name"].ToString();
string filestring = file.ToString();
if (filnames.Equals(filestring))
{
Response.Write("file already inserted");
readr.Close();
}
else
{
string text = System.IO.File.ReadAllText(path);
string[] lines = text.Split('\n');
//transctionscop
// DataTable dt = new DataTable();
// cmd = new SqlCommand();
string[] Values;
foreach (string line1 in lines)
{
if (line1 == "")
{
Response.Write("end file");
}
else
{
Values = line1.Split(';');
DateTime zero = Convert.ToDateTime(Values[0]);
// DateTime onezerofive = Convert.ToDateTime(Values[105]);
// DateTime onezerosix = Convert.ToDateTime(Values[106]);
// Timer two = Convert.Tot(Values[2]);
// string query = "INSERT INTO cdr_info VALUES ('" + Values[0] + "'," + Values[1] + ",'" + Values[2] + "','" + Values[3] + "'," +
string query = "INSERT INTO cdr_info VALUES( '" + zero + "', '" + Values[1] + "', '" + Values[2] + "', '" + Values[3] + "', '" + Values[4] + "', '" + Values[5] + "', '" + Values[6] + "', '" + Values[7] + "', '" + Values[8] + "', '" + Values[9] + "'," +
" '" + Values[10] + "', '" + Values[11] + "', '" + Values[12] + "', '" + Values[13] + "', '" + Values[14] + "','" + Values[15] + "', '" + Values[16] + "', '" + Values[17] + "', '" + Values[18] + "','" + Values[19] + "'," +
"'" + Values[20] + "','" + Values[21] + "', '" + Values[22] + "', '" + Values[23] + "', '" + Values[24] + "', '" + Values[25] + "','" + Values[26] + "', '" + Values[27] + "', '" + Values[28] + "', '" + Values[29] + "', " +
" '" + Values[30] + "', '" + Values[31] + "', '" + Values[32] + "', '" + Values[33] + "', '" + Values[34] + "'," +
"'" + Values[35] + "', '" + Values[36] + "', '" + Values[37] + "', '" + Values[38] + "','" + Values[39] + "', '" + Values[40] + "', '" + Values[41] + "', '" + Values[42] + "'," +
"'" + Values[43] + "', '" + Values[44] + "', '" + Values[45] + "', '" + Values[46] + "', '" + Values[47] + "', '" + Values[48] + "', '" + Values[49] + "','" + Values[50] + "', '" + Values[51] + "'," +
" '" + Values[52] + "', '" + Values[53] + "', '" + Values[54] + "', '" + Values[55] + "', '" + Values[56] + "','" + Values[57] + "', '" + Values[58] + "', '" + Values[59] + "', '" + Values[60] + "', '" + Values[61] + "'," +
"'" + Values[62] + "', '" + Values[63] + "', '" + Values[64] + "', '" + Values[65] + "', '" + Values[66] + "','" + Values[67] + "','" + Values[68] + "','" + Values[69] + "', '" + Values[70] + "'," +
"'" + Values[71] + "', '" + Values[72] + "','" + Values[73] + "','" + Values[74] + "', '" + Values[75] + "', '" + Values[76] + "', '" + Values[77] + "', '" + Values[78] + "', '" + Values[79] + "', '" + Values[80] + "'," +
" '" + Values[81] + "', '" + Values[82] + "', '" + Values[83] + "', '" + Values[84] + "', '" + Values[85] + "','" + Values[86] + "', '" + Values[87] + "','" + Values[88] + "', '" + Values[89] + "', '" + Values[90] + "'," +
" '" + Values[91] + "', '" + Values[92] + "', '" + Values[93] + "', '" + Values[94] + "', '" + Values[95] + "', '" + Values[96] + "', '" + Values[97] + "', '" + Values[98] + "', '" + Values[99] + "', '" + Values[100] + "'," +
" '" + Values[101] + "', '" + Values[102] + "', '" + Values[103] + "'," +
" '" + Values[104] + "', '" + Values[105] + "', '" + Values[106] + "', '" + Values[107] + "', '" + Values[108] + "')";
// string query = "INSERT INTO demooo VALUES ('" + Values[0] + "','" + Values[1] + "','" + Values[2] + "')";
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
}
}
}
}
readr.Close();
}
The reader is already open. When you call ExecuteReader on the command, it returns an open data reader.
Why are you closing the data reader inside the loop though? You've got a Close call after the loop anyway so why close it twice? What you should do is create it with a using statement and then it will be implicitly closed at the end of the block.
i have another question for anyone willing to help. This should be fairly easy but for whatever reason i cant seem to get it right. Im working with visual studio 08 creating a asp.net website in c#
im trying to have a user register, which is all working great, and have the new user default as a user and not a admin. I am using a .MDB as where everything is stored.
is it possible to do this in my initial sql query?
currently my code looks like
strSQL = "Insert into tblUserLogin " +
"(UserFirstName, UserLastName, UserName, UserPassword, UserAddress, UserCity, UserState, UserZipCode, UserEmail, UserPhone, ) values ('" +
UserFirstName + "', '" + UserLastName + "', '" + UserName + "', '" + UserPassword + "', '" + UserAddress +
"', '" + UserCity + "', '" + UserState + "', '" + UserZipCode + "', '" + UserEmail + "', '" + UserPhone +
"')";
// set the command text of the command object
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// Execute the insert statement
command.ExecuteNonQuery();
this will successfully post everything to the .MDB and it will leave the cell under the column SecurityLevel empty.
i attempted to add
"(UserFirstName, UserLastName, UserName, UserPassword, UserAddress, UserCity, UserState, UserZipCode, UserEmail, UserPhone, SecurityLevel=U )
but this did not work as i hoped it would. Is there a simple way to have that value SecurityLevel default to U without anyone having to specify it?
thank you for your time
If I understand you correctly just use a const value 'U' for SecurityLevel column
strSQL = "INSERT INTO tblUserLogin " +
"(UserFirstName, UserLastName, " +
" UserName, UserPassword, " +
" UserAddress, UserCity, " +
" UserState, UserZipCode, " +
" UserEmail, UserPhone, SecurityLevel) " +
"VALUES (" +
UserFirstName + "', '" + UserLastName + "', '" +
UserName + "', '" + UserPassword + "', '" +
UserAddress + "', '" + UserCity + "', '" +
UserState + "', '" + UserZipCode + "', '" +
UserEmail + "', '" + UserPhone + "', 'U')"; // pass a const value for SecurityLevel column
// the rest of your code goes here
On a side note: Your code is vulnerable to sql-injections. Learn and use prepared (parameterized) statements instead of dynamically building a query strings.
Note: I'm building a practice project where my trainer has forbid me to parameterize. I am aware of the security risks, but the site will not be deployed. I'm using a select scope_identity method to grab an auto-incremented value from the SubmissionId column of my table Submissions.
I want to insert that value into two other tables; I've got newSubID declared as a var and I use it in the insert statements, but I get the error message
The name "newSubID" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
What am I missing here?
Here's my code:
protected void BtnSubmit_Click(object sender, EventArgs e)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
String subQuery = "INSERT INTO Submission (Coverage, CurrentCoverage, PrimEx, Retention, EffectiveDate, Commission, Premium, Comments) VALUES ('" + TbCoverage.Text + "','" + TbCurrentCoverage.Text + "','" + TbPrimEx.Text + "','" + TbRetention.Text + "','" + TbEffectiveDate.Text + "','" + TbCommission.Text + "','" + TbPremium.Text + "','" + TbComments.Text + "')"
+ "SELECT CAST (SCOPE_IDENTITY() AS int)";
using (SqlConnection sqlConn = new SqlConnection(connectionString))
{
sqlConn.Open();
SqlCommand subCmd = new SqlCommand(subQuery, sqlConn);
using (subCmd)
{
subCmd.ExecuteNonQuery();
var newSubID = (Int32)subCmd.ExecuteScalar();
String custQuery = "INSERT INTO Customer (CustId, CustName, SicNaic, CustAdd, CustCity, CustState, CustZip, SubId) VALUES ('" + TbCustId.Text + "', '" + TbCustName.Text + "', '" + RblSicNaic.SelectedItem + "', '" + TbCustAddress.Text + "', '" + TbCustCity.Text + "', '" + DdlCustState.SelectedItem + "', '" + TbCustZip.Text + "', newSubID)";
String broQuery = "INSERT INTO Broker (BroId, BroName, BroAdd, BroCity, BroState, BroZip, EntityType, SubId) VALUES ('" + TbBroId.Text + "', '" + TbBroName.Text + "', '" + TbBroAddress.Text + "', '" + TbBroCity.Text + "', '" + DdlBroState.SelectedItem + "', '" + TbBroZip.Text + "', '" + DdlEntity.SelectedItem + "', newSubID)";
SqlCommand custCmd = new SqlCommand(custQuery, sqlConn);
SqlCommand broCmd = new SqlCommand(broQuery, sqlConn);
using (custCmd)
using (broCmd)
{
custCmd.ExecuteNonQuery();
broCmd.ExecuteNonQuery();
Response.Redirect("~/View.aspx?ProductId=" + newSubID);
}
This is called up on the next page like so (I have left the errors as they are in the interest of helping whomever may need to see the problem and solutions, which are listed in answers below):
string x = Request.QueryString["SubmissionId"];
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string editCustQuery = "SELECT CustName, SicNaic, CustCity, CustAdd, CustState, CustZip FROM Customer WHERE SubId =" + x;
using (SqlConnection editConn = new SqlConnection(connectionString))
{
editConn.Open();
using (SqlCommand CustCommand = new SqlCommand(editCustQuery, editConn))
{
SqlDataReader dr = CustCommand.ExecuteReader();
dr.Read();
LblCustName.Text = dr.GetString(0);
LblSicNaic.Text = dr.GetString(1);
LblCustCity.Text = dr.GetString(2);
LblCustAddress.Text = dr.GetString(3);
LblCustState.Text = dr.GetString(4);
LblCustZip.Text = dr.GetInt32(5).ToString();
}
It's because you're not concatenating the newSubID into the custQuery / btoQuery SQL statements, but instead your using the literal text "newSubID" in the statement which is invalid here as it will assume "newSubID" is a column name.
i.e.
String custQuery = "INSERT INTO Customer (CustId, CustName, SicNaic, CustAdd, CustCity,
CustState, CustZip, SubId)
VALUES ('" + TbCustId.Text + "', '" + TbCustName.Text + "', '" + RblSicNaic.SelectedItem +
"', '" + TbCustAddress.Text + "', '" + TbCustCity.Text + "', '" +
DdlCustState.SelectedItem + "', '" + TbCustZip.Text + "'," +
newSubID.toString() + ")";
Of course, I'm only giving an answer that uses dynamic SQL like this because of your disclaimer and is not what I'd do in real life!
Answer of AdaTheDev is correct.
I think you have another issue. If you do ExecuteNonQuery and then ExecuteScalar with the same command, you'll insert twice. Use an out-parameter for your scope_id and call only exenonquery or call just exescalar.
//subCmd.ExecuteNonQuery();
var newSubID = (Int32)subCmd.ExecuteScalar();