I want to get Data table values and save them in a single string, where dt.rows.Count is more that 0.
I want get menu_name, menu_Quantity and store them into a single string where email=ariffnaj#gmail.com.
If this is possible, can you show how to do it, this code only save into string at first column only
SqlConnection conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["connectionString"].ConnectionString);
string cartsql = "SELECT menu_name,menu_price,menu_quantity FROM cart where email=#email";
SqlCommand cmd1 = new SqlCommand(cartsql, conn);
cmd1.Parameters.AddWithValue("#email", Session["email"].ToString());
SqlDataAdapter sda = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
foreach (DataRow dtRow in dt.Rows)
{
string menuname = dtRow["menu_name"].ToString();
string menuprice = dtRow["menu_price"].ToString();
string menuquantity = dtRow["menu_quantity"].ToString();
}
}
You can try coalesce function:
DECLARE #str nvarchar(MAX)
SELECT #str = (COALESCE(#str + ';', '') + CONCAT('Menu:', menu_name, ', Quantity:', menu_quantity))
FROM cart WHERE email=#email
SELECT #str as output
And then use:String str = cmd1.ExecuteScalar().ToString();
My solution uses a SqlDataReader instead of SqlDataAdapter and DataTable. This is easier, if you only want to retrieve some values. To build the string I use a StringBuilder, as it manages the resources better than string concatenation would.
public string GetCartStringForEMail(string email)
{
const string sql = "SELECT menu_name, menu_quantity FROM cart WHERE email=#email";
string connectionString =
ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using (var conn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, conn)) {
var sb = new StringBuilder();
cmd.Parameters.AddWithValue("#email", email);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) {
sb.Append(reader.GetString(0))
.Append(", ")
.AppendLine(reader.GetInt32(1).ToString());
}
return sb.ToString();
}
}
Note that the using-statements automatically close the connection and release the resources.
Related
I am trying to store sql data that I have for a voucher id and voucher amount into a variable and display it into a label on a click of a button.
protected void Button1_Click(object sender, EventArgs e)
{
string voucherId = String.Empty;
string voucherAmount = String.Empty;
string queryVoucherId = "select voucherid from ReturnForm where email = '" + Session["username"] + "';";
string queryVoucherAmount = "select voucheramount from ReturnForm where email = '" + Session["username"] + "';";
int index = 0;
using (SqlConnection con = new SqlConnection(str))
{
SqlCommand cmd = new SqlCommand(queryVoucherId, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
voucherId = reader[index].ToString();
index++;
}
}
using (SqlConnection con = new SqlConnection(str))
{
SqlCommand cmd = new SqlCommand(queryVoucherAmount, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
voucherAmount = reader[index].ToString();
index++;
}
}
if (txtVoucher.Text == voucherId)
{
Label3.Visible = true;
Label3.Text = voucherAmount;
}
}
When I click the button its giving me an error saying that the index is out of bounds.
Building on #JSGarcia's answer - but using parameters as one ALWAYS should - you'd get this code:
string email = Session['username'];
string query = $"SELECT voucherid, voucheramount FROM ReturnFrom WHERE Email = #email";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
// set the parameter before opening connection
// this also defines the type and length of parameter - just a guess here, might need to change this
cmd.Parameters.Add("#email", SqlDbType.VarChar, 100).Value = email;
conn.Open();
sda.Fill(dt);
conn.Close();
}
Personally, I'd rather use a data class like
public class VoucherData
{
public int Id { get; set; }
public Decimal Amount { get; set; }
}
and then get back a List<VoucherData> from your SQL query (using e.g. Dapper):
string query = $"SELECT Id, Amount FROM ReturnFrom WHERE Email = #email";
List<VoucherData> vouchers = conn.Query<VoucherData>(query).ToList();
I'd try to avoid the rather clunky and not very easy to use DataTable construct...
I strongly recommend combining your sql queries into a single one, write it into a datatable and continue your logic from there. IMHO it is much cleaner code:
string email = Session['username'];
string query = $"SELECT voucherid, voucheramount FROM ReturnFrom where Email = '{email}'";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = conn.CreateCommand())
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
conn.Open();
sda.Fill(dt);
conn.Close();
}
// Work with DataTable dt from here on
...
Well, one more big tip?
You ONLY as a general rule need a dataadaptor if you going to update the data table.
And you ONLY need a new connection object if you say not using the sql command object.
The sqlcommand object has:
a connection object - no need to create a separate one
a reader - no need to create a separate one.
Note how I did NOT create a seperate connection object, but used the one built into the command object.
And since the parameter is the SAME in both cases? Then why not re-use that too!!
So, we get this:
void TestFun2()
{
String str = "some conneciton???";
DataTable rstVouch = new DataTable();
using (SqlCommand cmdSQL =
new SqlCommand("select voucherid from ReturnForm where email = #email",
new SqlConnection(str)))
{
cmdSQL.Parameters.Add("#email", SqlDbType.NVarChar).Value = Session["username"];
cmdSQL.Connection.Open();
rstVouch.Load(cmdSQL.ExecuteReader());
// now get vouch amount
cmdSQL.CommandText = "select voucheramount from ReturnForm where email = #email";
DataTable rstVouchAmount = new DataTable();
rstVouchAmount.Load(cmdSQL.ExecuteReader());
if (rstVouch.Rows[0]["vourcherid"].ToString() == txtVoucher.Text)
{
Label3.Visible = true;
Label3.Text = rstVouchAmount.Rows[0]["voucheramount"].ToString();
}
}
}
Background
I've written a function that retrieves data using a SQL query and then outputs that data to a label. At the moment the search string is hard coded to "1002". The function is fired on a button click event.
Question
How do I pass data into my SQL query from a textbox so my search string is the contents of the text box, instead of 1002?
Code
private void getInfoStationID()
{
String ConnStr = "Data Source=SqlServer; Initial Catalog=Database; User ID=Username; Password=Password";
String SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = 1002";
SqlDataAdapter Adpt = new SqlDataAdapter(SQL, ConnStr);
DataSet question = new DataSet();
Adpt.Fill(question);
foreach (DataRow dr in question.Tables[0].Rows)
{
nameTtb.Text += question.Tables[0].Rows[0]["stationname"].ToString();
}
}
Change the query to:
string constring = #""; // Declare your connection string here.
String SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = #StationId";
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand command = new SqlCommand(SQL ,con);
and then you have to add parameter to the command object like this:
command .Parameters.Add("#StationId",SqlDbType.NVarChar).Value = textbox.Text;
Now you might be wondering why I have used parameters in the query. It is to avoid SQL Injection.
DataSet ds = new DataSet();
SqlDataAdapter adb = new SqlDataAdapter(command);
adb.Fill(ds);
con.Close();
And now you can iterate like this...
foreach (DataRow row in ds.Tables[0].Rows)
{
}
And you have to initialise the connection object and pass your connection string in it.
You can change your SQL string to use a variable, like #StationID, then add the variable to the query from textbox.text
String SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = #StationID";
SqlCommand cmd = new SqlCommand;
cmd.CommandText = SQL;
cmd.CommandType = CommandType.Text;
cmd.Connection = ConnStr;
cmd.Parameters.AddWithValue("#StationID", Textbox1.Text);
da = new SqlDataAdapter(cmd);
DataSet nds = new DataSet();
da.Fill(nds);
String ConnStr = "Data Source=SqlServer; Initial Catalog=Database; User ID=Username; Password=Password";
string SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = #stationID";
SqlCommand command = new SqlCommand(SQL, ConnStr);
command.Parameters.Add(new SqlParameter("#stationID", SqlDbType.Int));
command.Parameters["#stationID"].Value = textbox.Text;
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();
Why do I get this exception in my code? I restarted the server, changed ports, etc, but nothing is working.
What's wrong?
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection("server=localhost;user=armin;password=root;");
con.Open();
SqlCommand result = new SqlCommand(
"SELECT userid FROM KDDData.dbo.userprofile order by userid", con);
SqlDataReader reader = result.ExecuteReader();
dt.Load(reader);
List<string> userids = new List<string>(dt.Rows.Count);
foreach (DataRow item in dt.Rows)
{
userids.Add(item.ItemArray[0].ToString().Trim());
}
con.Close();
con = new SqlConnection("server=localhost;user=armin;password=root;");
con.Open();
foreach (string user in userids)
{
DataTable temp = new DataTable();
SqlCommand result1 = new SqlCommand(
"select itemid from KDDTrain.dbo.train where userid=" + user, con);
SqlDataReader reader1 = result1.ExecuteReader();
if (!reader1.HasRows)
{
continue;
}
temp.Load(reader1);
}
The first query works fine, but the second doesn't. As you can see I even use some other SqlConnection but it still doesn't work.
Note:The database i'm working with has atleast 100 milion records,thought may be this would be a problem.
Something doesn't look right in your connection string
I always seen "server=localhost; user=armin;password=root" in connections strings for MySql not for SqlServer where instead I will use "Data Source=(LOCAL);Integrated Security=SSPI" or the INSTANCE name of SqlServer. Are you sure that the first query works?.
However I think you should use the appropriate using statement
DataTable dt = new DataTable();
using(SqlConnection con = new SqlConnection("server=localhost;user=armin;password=root;"))
{
using(SqlCommand result = new SqlCommand(
"SELECT userid FROM KDDData.dbo.userprofile order by userid", con))
{
con.Open();
using(SqlDataReader reader = result.ExecuteReader())
{
dt.Load(reader);
List<string> userids = new List<string>(dt.Rows.Count);
foreach (DataRow item in dt.Rows)
{
userids.Add(item.ItemArray[0].ToString().Trim());
}
}
DataTable temp = new DataTable();
foreach (string user in userids)
{
using(SqlCommand result1 = new SqlCommand(
"select itemid from KDDTrain.dbo.train where userid=" + user, con))
{
using(SqlDataReader reader1 = result1.ExecuteReader())
{
if (!reader1.HasRows) continue;
temp.Load(reader1);
}
}
}
}
Please insert this line
result1.CommandTimeout = 0;
befor this line in the second query
SqlDataReader reader1 = result1.ExecuteReader();
Dispose your reader after:
foreach (DataRow item in dt.Rows)
{
userids.Add(item.ItemArray[0].ToString().Trim());
}
...and also close the connection after temp.Load(reader1). Also close the reader1.
Instead of all this... the clean way is to use USING for initializng the readers and connection. :)
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.