SQL Count from specific Column in Database - sql

I want to get a SQL Count of the number of records that pertain to my bundnum column and display it into my textblock. Any suggestions?
SqlConnection conn = new SqlConnection("db connection");
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "SELECT COUNT(*) FROM dbo.tablename WHERE bundnum = 'values' ";
conn.Open();
int returnValue = (int)comm.ExecuteScalar();
txtNumber.Text = returnValue.ToString();

Using Google, I found this helpful link and after some modification:
Int32 newCount = 0;
string newValue = "something";
string sql =
"SELECT COUNT(*) FROM dbo.tablename WHERE bundnum = '#myValue'";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#myValue", SqlDbType.VarChar);
cmd.Parameters["#myValue"].Value = newValue;
try
{
conn.Open();
newCount = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

Related

How to query SQL to RichEditControl DevExpress?

I want to fill data from SQL Server to RichEditControl.Text. I used this code but it doesn't work, my RichEditControl.Text has an empty string.
string connectionstring = "Data Source=ADMIN;Initial Catalog=Shoplacviet;Integrated Security=True";
SqlConnection conn = new SqlConnection(connectionstring);
conn.Open();
string query = "select * from so";
SqlCommand cmd = new SqlCommand(query, conn);
var reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
richEditControl1.Options.MailMerge.DataSource = dt;
richEditControl1.Options.MailMerge.ViewMergedData = true;
richEditControl1.Text = dt.ToString();
conn.Close();

How to use SqlDataSource with button on click to get results from gridview

My overall goal is to be able to type in information into my textbox and click a button to search and get results from the database using gridview. So far I have my SqlDataSource SQL statement set up. I need to figure out how to link my button on click event with my SqlDataSource and Textbox.
Here is what I have so far:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("Data Source=********;Initial Catalog=*******;User ID=*******;Password=*******");
connection.Open();
}
I am not sure how to use my SqlDataSource that I have already set up.
Updated Code:
SqlConnection sqlCon = new SqlConnection("*******");
SqlDataAdapter dt = new SqlDataAdapter();
DataSet ds = new DataSet();
try
{
sqlCon.Open();
dt.SelectCommand = new SqlCommand("SELECT* FROM Core.Form_Section_SubSection_Item_Rel WHERE ([DataCollectionPeriodID] = #DataCollectionPeriodID)", sqlCon);
dt.Fill(ds);
sqlCon.Close();
GridView1.DataBind();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
I will advice you use are stored proc with a parameter and do something like below but you can change this to use your select query, just change commandtype
using (SqlConnection sqlCon = new SqlConnection("connection string"))
{
using (SqlCommand cmd = new SqlCommand())
{
sqlCon.Open();
cmd.Connection = sqlCon;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT* FROM Core.Form_Section_SubSection_Item_Rel WHERE DataCollectionPeriodID = #DataCollectionPeriodID";
cmd.CommandTimeout = 30;
cmd.Parameters.Add("#DataCollectionPeriodID", SqlDbType.VarChar).Value = TextBox1.Text
SqlDataAdapter dt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dt.Fill(ds);
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
}

Select SCOPE_IDENTITY not executing after insert statement;

I try to get the id of the last inserted t ouristin the table as I put Selct SCOPE_IDENTITY; after the insert query.
The problem is that when I try to show the id of the inserted tourist in the label - just nothing happens. (only the insert query is executed);
string insertSQL = "INSERT INTO Tourist (Excursion_ID, Excursion_date_ID, Name_kir,Midname_kir, Lastname_kir)";
insertSQL += "VALUES (#Excursion_ID, #Excursion_date_ID, #Name_kir,#Midname_kir, #Lastname_kir);Select SCOPE_IDENTITY()";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=excursion;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#Excursion_ID", Convert.ToInt32(mynew2));
cmd.Parameters.AddWithValue("#Excursion_date_ID", Convert.ToInt32(mynewnewstring));
cmd.Parameters.AddWithValue("#Name_kir",tx888.Text);
cmd.Parameters.AddWithValue("#MidName_kir",tx888_1.Text);
cmd.Parameters.AddWithValue("#LastName_kir",tx888_2.Text);
int added = 0;
try
{
con.Open();
added = (int)cmd.ExecuteScalar();
if (added > 0)
{
lblproba.Text+=added.ToString();
}
}
catch (Exception ex)
{
//lblResult.Text = ex.Message;
}

"Invalid object name" error in adapter.Fill method

I'm trying to make a DataSet from all tables of the AdventureWorks2012 database. But I'm getting an "Invalid object name " error in the adapter.Fill method.
Any ideas?
private void openDBButton_Click(object sender, RoutedEventArgs e)
{
DataSet myDataSet = new DataSet();
SqlDataAdapter myDataAdapter;
SqlCommand myCommand;
string conStr = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + dbPath.Text +
";Integrated Security=true";
SqlConnection connection = new SqlConnection(conStr);
connection.Open();
DataTable tables = connection.GetSchema("Tables");
foreach (DataRow table in tables.Rows)
{
if (table["TABLE_TYPE"].ToString() != "BASE TABLE")
continue;
string tableName = table["TABLE_NAME"].ToString();
string sqlCmd = "SELECT * FROM " + "[" + tableName + "]";
//SqlDataAdapter adapt = new SqlDataAdapter(new SqlCommand(sqlCmd, connection));
//adapt.FillSchema(myDataSet, SchemaType.Mapped, tableName);
myCommand = new SqlCommand(sqlCmd, connection);
myDataAdapter = new SqlDataAdapter(myCommand);
myDataAdapter.Fill(myDataSet, tableName); // here i'm get in trouble :)
}
}

How to get a dataset value

New to VB.Net,
How to insert or select the dataset value.
cmd = New SqlCommand("Select * from table1", con)
ada = New SqlDataAdapter(cmd)
ds = New DataSet
ada.Fill(ds)
cmd = New SqlCommand("Select * from '" & ds.Tables(0) & "' ", con)
mydatatable1.Load(dr3)
It was showing the error in '" & ds.Tables(0) & "', I want to get the dataset value
Need VB.Net Code Help
You have a reasonable idea right up until you get to the point where you are trying to create a second SqlCommand. That is, once you do the Fill, you already have the data in a table. You wouldn't run another select - you've already done that. You'd just reference the table that you want to use in the dataset.
If you want a data table you would do something like this (for VB, see below):
SqlDataAdapter myAdapter = new SqlDataAdapter(CommandText, con);
DataSet myDataset = new DataSet();
myAdapter.Fill(myDataset, "Table"); // "Table" is just a name, it can be anything.
mydatatable1 = myDataset.Tables[0]; // Get the table
Now, if you don't need a DataTable, per se, but just want to read from the query, you'd use a SqlDataReader:
cmd = new SqlCommand(CommandText, con);
// One or more params
cmd.Parameters.AddWithValue("#paramName", Value);
SqlDataReader nwReader = cmd.ExecuteReader();
Then just read from the nwReader:
while (nwReader.Read())
{
string field1Val = (string)nwReader["FieldName"];
etc...
}
Update: I don't know VB but here is what I think it would look like:
cmd = New SqlCommand("Select * from table1", con)
ada = New SqlDataAdapter(cmd)
ds = New DataSet
ada.Fill(ds)
mydatatable1 = ds.Tables(0);
You may well be able to shorten this to get rid of the extra SqlCommand (assuming VB supports this SqlDataAdapater syntax like C#.
ada = New SqlDataAdapter("Select * from table1", con)
ds = New DataSet
ada.Fill(ds)
mydatatable1 = ds.Tables(0);
Good luck...
you can use Microsoft Enterprise Library for making easy this process. this library is a powerful library for working with datasets.
public async Task<ResponseStatusViewModel> GetAll()
{
var responseStatusViewModel = new ResponseStatusViewModel();
var connection = new SqlConnection(EmployeeConfig.EmployeeConnectionString);
var command = new SqlCommand("usp_GetAllEmployee", connection);
command.CommandType = CommandType.StoredProcedure;
try
{
await connection.OpenAsync();
var reader = await command.ExecuteReaderAsync();
var dataSet = new DataSet();
dataSet.Load(reader, LoadOption.OverwriteChanges, new string[] { "Employee" });
reader.Close();
reader.Dispose();
var employees = new List<EmployeeModel>();
if (dataSet.Tables.Count > 0 && dataSet.Tables["Employee"] != null)
{
var employeeTable = dataSet.Tables["Employee"];
for (int i = 0; i < employeeTable.Rows.Count; i++)
{
var employeeRow = employeeTable.Rows[i];
employees.Add(new EmployeeModel
{
EmployeeID = Convert.ToInt32(employeeRow["EmployeeID"]),
EmployeeName = Convert.ToString(employeeRow["EmployeeName"]),
Address = Convert.ToString(employeeRow["Address"]),
GrossSalary = Convert.ToDouble(employeeRow["GrossSalary"]),
PF = Convert.ToDouble(employeeRow["PF"]),
TotalSalary = Convert.ToDouble(employeeRow["TotalSalary"])
});
}
}
responseStatusViewModel.Data = employees;
command.Dispose();
connection.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return responseStatusViewModel;
}
I think what you are looking for is
cmd = New SqlCommand("Select * from '" & ds.Tables(0).TableName & "' ", con)
cmd = New SqlCommand("Select * from table1", con)
ada = New SqlDataAdapter(cmd)
ds = New DataSet
ada.Fill(ds)
cmd = New SqlCommand("Select * from '" & ds.Tables(0).TableName & "' ", con)
mydatatable1.Load(dr3)