I have an issue with assigning values.
string userlanguages = string.Empty;
try
{
SqlCommand cmd = new SqlCommand("SELECT [s_langName] from [dbo].[tx_UserLanguages] WHERE [s_ID] ='" + Class1.EmployeeId + "'", objcon);
if (objcon.State == ConnectionState.Closed) objcon.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDS = new DataSet();
adp.Fill(myDS);
userlanguages = myDS.Tables[0].Rows[0]["[s_langName]"].ToString();
}
catch (SqlException exc)
{
Response.Write(exc.Message);
}
finally
{
objcon.Close();
Class1.langKnwn = userlanguages;
}
}
Suppose, Here the myDs contains three values. Then how will i assign them to a single string(in this case 'userlanguages'). I am using the Class1.langKnwn in another page to display the user selected languages(which may be more than 1 language in many cases).
Please help me.
How about somethig like
List<string> languages = new List<string>();
for (int iRow = 0; iRow < myDS.Tables[0].Rows.Count; iRow++)
languages.Add(myDS.Tables[0].Rows[iRow]["[s_langName]"].ToString());
userlanguages = String.Join(",", languages);
SqlCommand cmd = new SqlCommand("SELECT [s_langName] from [dbo].[tx_UserLanguages] WHERE [s_ID] ='" + Class1.EmployeeId + "'", objcon);
if (objcon.State == ConnectionState.Closed) objcon.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDS = new DataSet();
adp.Fill(myDS);
for(int ndx=0;ndx<myDS.Tables[0].Rows.Count;ndx+=1)
{
if(ndx==0)
{
userlanguages = myDS.Tables[0].Rows[ndx]["[s_langName]"].ToString();
}
else
{
userlanguages = userlanguages+","+ myDS.Tables[0].Rows[ndx]["[s_langName]"].ToString();
}
}
userlanguages = string.Join(",", myDS.Tables[0].AsEnumerable()
.Select(row => row.Field<string>("[s_langName]"))
.ToArray());
If I understand your question correctly, using SqlDataReader could be better option in your case.
using (SqlConnection objcon= new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SELECT [s_langName] from [dbo].[tx_UserLanguages] WHERE [s_ID] = #id", objcon);
cmd.Parameters.AddWithValue("#id", Class1.EmployeeId);
connection.Open();
SqlDataReader reader = cmd .ExecuteReader();
string userlanguages = string.Empty;
while (reader.Read())
{
string str = reader.GetString(0);
userlanguages = String.Join(",", userlanguages);
}
reader.Close();
}
And you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Try this
Use using System.Text; namesapce
and then write that code in your block
StringBuilder sb = new StringBuilder();
for (int iRow = 0; iRow < myDS.Tables[0].Rows.Count; iRow++)
{
sb.Append(myDS.Tables[0].Rows[iRow]["[s_langName]"].ToString());
sb.Append(",");
}
// to get the string at the end
string myString = sb.ToString();
myString= myString.Substring(0, myString.Length - 1);
Related
I've got the following code:
private void btnAddMatter_Click(object sender, EventArgs e)
{
MatterCode = "";
EntityID = 0;
FeeEarnerID = 0;
OpenedByUserID = 0;
CompanyContactDetailsID = 0;
Description = "";
OurReference = "";
TheirReference = "";
DateOpened = DateTime.Now;
MatterTypeID = 0;
DepartmentID = 0;
ResponsibleUserID = 0;
TrustBankAccountID = 0;
BusinessBankAccountID = 0;
string connectionString = "Data Source=***\\SQLEXPRESS;Initial Catalog=STUPELG;Persist Security Info=True;User ID=***;Password=***";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Matter ( MatterCode, EntityID, FeeEarnerID, OpenedByUserID, CompanyContactDetailsID, Description," +
" OurReference, TheirReference, DateOpened, MatterTypeID, DepartmentID, ResponsibleUserID, TrustBankAccountID, BusinessBankAccountID)" +
" VALUES ( #MatterCode, #EntityID, #FeeEarnerID, #OpenedByUserID, #CompanyContactDetailsID, #Description," +
" #OurReference, #TheirReference, #DateOpened, #MatterTypeID, #DepartmentID, #ResponsibleUserID, #TrustBankAccountID, #BusinessBankAccountID);" +
" SELECT SCOPE_IDENTITY();");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#MatterID", MatterID);
cmd.Parameters.AddWithValue("#MatterCode", MatterCode);
cmd.Parameters.AddWithValue("#EntityID", EntityID);
cmd.Parameters.AddWithValue("#FeeEarnerID", FeeEarnerID);
cmd.Parameters.AddWithValue("#OpenedByUserID", OpenedByUserID);
cmd.Parameters.AddWithValue("#CompanyContactDetailsID", CompanyContactDetailsID);
cmd.Parameters.AddWithValue("#Description", Description);
cmd.Parameters.AddWithValue("#OurReference", OurReference);
cmd.Parameters.AddWithValue("#TheirReference", TheirReference);
cmd.Parameters.AddWithValue("#MatterTypeID", MatterTypeID);
cmd.Parameters.AddWithValue("#DepartmentID", DepartmentID);
cmd.Parameters.AddWithValue("#ResponsibleUserID", ResponsibleUserID);
cmd.Parameters.AddWithValue("#TrustBankAccountID", TrustBankAccountID);
cmd.Parameters.AddWithValue("#BusinessBankAccountID", BusinessBankAccountID);
cmd.Parameters.AddWithValue("#DateOpened", DateOpened);
connection.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet NewMatterID = new DataSet();
adapter.Fill(NewMatterID);
MatterCode = Convert.ToString(NewMatterID.Tables[0].Rows[0][0]);
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("UPDATE Matter SET MatterCode = #MatterCode WHERE MatterID = " + MatterCode);
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#MatterCode", MatterCode);
connection.Open();
cmd.ExecuteNonQuery();
}
MessageBox.Show("Matter " + MatterCode + " successfully created");
}
After the row is inserted, the new MatterID (primary key that is generated automatically) should be copied to the MatterCode field. Currently it works EXCEPT that there is an extra row that is generated at when the button is clicked:
How do I fix this???
Well - this is because your code is executing the INSERT query twice......
connection.Open();
cmd.ExecuteNonQuery(); // first execution
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet NewMatterID = new DataSet();
adapter.Fill(NewMatterID); // second execution
I'm not entirely sure what you wanted to do with that SqlDataAdapter - but it's using the same SqlCommand from before, with the INSERT statement, which gets executed a second time......
You can replace this:
cmd.ExecuteNonQuery();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet NewMatterID = new DataSet();
adapter.Fill(NewMatterID);
MatterCode = Convert.ToString(NewMatterID.Tables[0].Rows[0][0]);
with
MatterCode = cmd.ExecuteScalar().ToString();
as ExecuteScalar runs the command and returns the value of the first column of the first row of the first resultset.
Iam trying to print data base value and the radio buttons in to a div but my problem is first if there are no rows in the table i need to show that there are no rows and the second probllem i want to add for (i = 0; i <= dt.Rows.Count - 1; i++) for condition as am using radio buttons that are dynamically generated i need to add i means number to each fetch.
string xxx= SessionManager.xxxxxxxx;
string htmlStr = "";
using (MySqlConnection myConnection = new MySqlConnection(constr))
{
string oString = "Select * from xxxxx WHERE xxxx=#xxxx and xxxx=#xxxx ";
MySqlCommand oCmd = new MySqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("#xxxx", "0");
oCmd.Parameters.AddWithValue("#xxxx", "0");
myConnection.Open();
using (MySqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
string Name = oReader["xxxx"].ToString();
// string Pass = oReader["xxxx"].ToString();
htmlStr += "<tr><td>" + Name + "</td><td><input type='radio' name='Present' value='Present'></td><td><input type='radio' name='Absent' value='Absent'></td><td><input type='radio' name='Leave' value='Leave'></td></tr>";
}
myConnection.Close();
}
}
STUDENT_LIST.InnerHtml = htmlStr;
MySqlDataReader has a readonly property called as "HasRows". The usage of it is;
if(oReader.HasRows)
{
// Perform operation
}
else
// Some other operation
The link for detailed list of members and methods of MySqlDataReader is here
UPDATE:
If you are looking for an example for the usage of MySqlDataAdapter, I would suggest you to go through the DataSet & MySqlDataAdapter section of this link
Hope this helps.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("select * from your_table", con);
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
int num = ds.Tables[0].Rows.Count;
for (int i = 0; i < num - 1; i++)
//Do something here
}
catch (Exception ex)
{
//...
}
finally
{
con.Close();
}
Hope it helps
Issue with List.Add(): it only saves the last added item, it binds the last data repeatedly, please someone help me to clear it. I am trying out in mvc 4 as Begineer. I am also struggling with basic of mvc 4. thank u in advance.
var modelList = new List<MyCourseData>();
string batchid = System.Web.HttpContext.Current.Request.QueryString["batchid"];
SqlConnection con = null;
string result = "";
DataSet ds = null;
con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
SqlCommand cmd = new SqlCommand("select * from [Student].[dbo].[tbl_batch] where batchid=#batchid", con);
//cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#batchid", batchid);
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
ds = new DataSet();
da.Fill(ds);
con.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var model = new MyCourseData();
var classdates = ds.Tables[0].Rows[i]["class_dates"].ToString();
int j = 0;
// string[] parts = classdates.Split(',');
foreach (string CourseDates in classdates.Split(','))
{
model.batchid = ds.Tables[0].Rows[i]["batchid"].ToString();
model.course = ds.Tables[0].Rows[i]["course"].ToString();
model.trainer = ds.Tables[0].Rows[i]["trainer"].ToString();
model.class_dates = CourseDates;
modelList.Add(model);
}
}
return modelList;
This happens because you are adding the same instance of MyCourseData in the list with value changing in every iteration.
You need to create new instance of MyCourseData for every iteration,
var modelList = new List<MyCourseData>();
string batchid = System.Web.HttpContext.Current.Request.QueryString["batchid"];
SqlConnection con = null;
string result = "";
DataSet ds = null;
con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
SqlCommand cmd = new SqlCommand("select * from [Student].[dbo].[tbl_batch] where batchid=#batchid", con);
//cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#batchid", batchid);
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
ds = new DataSet();
da.Fill(ds);
con.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var classdates = ds.Tables[0].Rows[i]["class_dates"].ToString();
int j = 0;
// string[] parts = classdates.Split(',');
foreach (string CourseDates in classdates.Split(','))
{
var model = new MyCourseData();
model.batchid = ds.Tables[0].Rows[i]["batchid"].ToString();
model.course = ds.Tables[0].Rows[i]["course"].ToString();
model.trainer = ds.Tables[0].Rows[i]["trainer"].ToString();
model.class_dates = CourseDates;
modelList.Add(model);
}
}
return modelList;
}
How to count the number of rows from sql table in c#?
I need to extract some data from my database...
You may try like this:
select count(*) from tablename where columname = 'values'
C# code will be something like this:-
public int A()
{
string stmt = "SELECT COUNT(*) FROM dbo.tablename";
int count = 0;
using(SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"))
{
using(SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
}
}
return count;
}
You need to make a database connection from c# first. Then, you need to pass below query as commandText.
Select count(*) from TableName
Use ExecuteScalar/ExecuteReader to get the returned count.
Do you means likes this ?
SELECT COUNT(*)
FROM yourTable
WHERE ....
You can make global function that you can use all the time as
public static int GetTableCount(string tablename, string connStr = null)
{
string stmt = string.Format("SELECT COUNT(*) FROM {0}", tablename);
if (String.IsNullOrEmpty(connStr))
connStr = ConnectionString;
int count = 0;
try
{
using (SqlConnection thisConnection = new SqlConnection(connStr))
{
using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
}
}
return count;
}
catch (Exception ex)
{
VDBLogger.LogError(ex);
return 0;
}
}
This works for me
using (var context = new BloggingContext())
{
var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();
}
For more information consult: https://learn.microsoft.com/es-es/ef/ef6/querying/raw-sql?redirectedfrom=MSDN
Use this its working
string strQuery = "SELECT * FROM staff WHERE usertype='lacturer'";
connect.Open();
SqlCommand cmd = new SqlCommand(strQuery, connect);
SqlDataAdapter OleDbDa = new SqlDataAdapter(cmd);
DataSet dsData = new DataSet();
OleDbDa.Fill(dsData);
connect.Close();
std.Text = dsData.Tables[0].Rows.Count.ToString();
I used this method in my own application to count the number of active users within the program. This can be easily manipulated for your own use.
con.open();
string ActiveUsers = "SELECT * FROM Devices WHERE Status='" + "Online" + "'";
SqlCommand cmd = new SqlCommand(ActiveUsers, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
con.Close();
Users.Text = ds.Tables[0].Rows.Count.ToString();
Friends expecting ur suggetions to the below code. Instead of taking dtr1( DatatableReader) it is taking outside loop dtr(DataTableReader) Table.
protected void GetStudReport(Object o, EventArgs e)
{
if (mycon.State != ConnectionState.Open)
{
List<string> lstQstn = new List<string>();
mycon.Open();
cmd = new MySqlCommand("SELECT * from scord_mark_table where stu_ID='" + drpDnSearch3.SelectedValue + "'", mycon);
MySqlDataReader rdr1=cmd.ExecuteReader();
DataSet ds=new DataSet();
DataTable dtScrTbl=new DataTable();
dtScrTbl.Load(rdr1);
ds.Tables.Add(dtScrTbl);
rdr1.Close();
cmd = null;
int i = 0;
Dictionary<string, string> dctSub = new Dictionary<string, string>();
**using (DataTableReader dtr = ds.CreateDataReader())**
{
while (dtr.Read())
{
lstQstn.Add(dtr["test_id"].ToString());
while (i <= lstQstn.Count())
{
MySqlCommand cmd2 = new MySqlCommand("SELECT test_id,subject_id from qution_no_table where test_id='" + lstQstn[i].ToString() + "'", mycon);
MySqlDataReader rdr2 = cmd2.ExecuteReader();
DataTable dtQsNoTbl = new DataTable();
dtQsNoTbl.Load(rdr2);
ds.Tables.Add(dtQsNoTbl);
**using (DataTableReader dtr1 = ds.CreateDataReader())**
{
while (dtr1.Read())
{
dctSub.Add(dtr1["test_id"].ToString(), dtr1["subject_id"].ToString()); // **here it is taking table scord_mark_table instead of dtr1's qution_no_table**
}
rdr2.Close();
break;
}
}
//cmd2 = null;
i++;
}
}
No, it's not - it's returning a new DataTableReader hooked to ALL of the existing tables (including the one you created before the first loop).
Try specifying the DataTable you want the readers attached to:
using (DataTableReader dtr = ds.CreateDataReader(dtScrTbl))
and
using (DataTableReader dtr1 = ds.CreateDataReader(dtQsNoTbl))