I want to using the code below and display in GridView.
The situation is, when user click on GET CURRENT DATE TRANS, GridView will display the today date as the result. I already insert the GridView id as GridView1
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=AXSQL;Initial Catalog=UniKL;User ID=aten;Password=pass#WORD1";
sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = cast(getdate() as date)";
GridView1.DataBind();
connection = new SqlConnection(connetionString);
connection.Open();
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
I guess your column SubmittedDateTime is of type DateTime in sql so you also need to cast this column in date to match the current date like this
cast([SubmmitedDateTime] as Date) = cast(getdate() as date);
So you query will look like this
sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE cast([SubmmitedDateTime] as Date) = cast(getdate() as date)";
You are not assigning data source to GridView1. Please use the following code:
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=AXSQL;Initial Catalog=UniKL;User ID=aten;Password=pass#WORD1";
sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = cast(getdate() as date)";
//GridView1.DataBind();
connection = new SqlConnection(connetionString);
connection.Open();
command = new SqlCommand(sql, connection);
//Get data into a reader
SqlDataReader sr = command.ExecuteReader();
//command.ExecuteNonQuery();
//Set the datasource of GridView1
GridView1.DataSource = sr;
GridView1.DataBind();
command.Dispose();
connection.Close();
One suggestion would be to change:
sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = cast(getdate() as date)";
to something like:
sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = " + DateTime.Now.toShortDateString();
or
sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = " + DateTime.Now.toString("yyyy-MM-dd");
Related
I'm trying to insert some records to 2 tables at same event
private void Btngravar_Click(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection("server=localhost;user id=root;database=saude;Password=");
conn.Open();
MySqlCommand objcmd = new MySqlCommand("insert into dispensacao (DESTINATARIO,COD_UNIDADE,COD_DEPARTAMENTO,DATA,SOLICITANTE,DEFERIDO_POR) values(?,?,?,?,?,?)", conn);
objcmd.Parameters.Add("#DESTINATARIO", MySqlDbType.VarChar, 45).Value = Cmbdestinatario.Text;
objcmd.Parameters.AddWithValue("#COD_UNIDADE", string.IsNullOrEmpty(Txtcodigounidade.Text) ? (object)DBNull.Value : Txtcodigounidade.Text);
objcmd.Parameters.AddWithValue("#COD_DEPARTAMENTO", string.IsNullOrEmpty(Txtcodigodep.Text) ? (object)DBNull.Value : Txtcodigodep.Text);
DateTime fdate = DateTime.Parse(Txtdata.Text);
objcmd.Parameters.Add("#DATA", MySqlDbType.DateTime).Value = fdate;
objcmd.Parameters.Add("#SOLICITANTE", MySqlDbType.VarChar, 45).Value = Txtsolicitante.Text;
objcmd.Parameters.Add("#DEFERIDO_POR", MySqlDbType.VarChar, 45).Value = Txtdeferido.Text;
objcmd.ExecuteNonQuery();
conn.Close();
conn.Open();
objcmd = new MySqlCommand("insert into produtos_disp(COD_DISPENSACAO,COD_PRODUTO,PRODUTO,QUANTIDADE) values (?,?,?,?)", conn);
string selectid = "select ifnull (max(ID),1) from dispensacao";
objcmd = new MySqlCommand(selectid, conn);
MySqlDataReader reader = objcmd.ExecuteReader();
if (reader.Read())
{
Txtcodigo.Text = reader.GetString("ID");
}
//Txtcodigo.DataBindings.Add("Text", dtid, "ID");
objcmd.Parameters.AddWithValue("#COD_DISPENSACAO", Txtcodigo.Text);
objcmd.Parameters.AddWithValue("#COD_PRODUTO", dtproddisp.Rows[0][0]);
objcmd.Parameters.AddWithValue("#PRODUTO", dtproddisp.Rows[0][1]);
objcmd.Parameters.AddWithValue("#PRODUTO", dtproddisp.Rows[0][2]);
Code from the comment
string selectQuery = "SELECT * from departamento";
connection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
DataTable dt2 = new DataTable();
dt2.Load(reader);
Cmbdestinatario.DisplayMember = "nome";
Cmbdestinatario.ValueMember = "CODIGO";
Cmbdestinatario.DataSource = dt2;
Txtcodigodep.DataBindings.Add("Text", dt2, "CODIGO");
The first part is working, I can see records inserted on dispensacao table, but the second isn't working, error:
Could not find specified column in results: ID
and I need to get products from datagridview,
App screen:
MySQL Dispensacao table:
My problem now is inserting those selected products from datagridview on database and get the id from dispensacao to insert on products table,
If you want to insert more rows in a database(from what I known), you should add a checkbox in a DataGridView Column and store checked rows to a list. Then you should use a for loop to insert each data to Database by list values.
If you want the code please comment me.
I am developing an application in C# where I'm trying to use Oracle Database Change Notification.
When I'm using DCN for one table, everything is working as expected but when I am trying to use two tables, I get the following error: "Attempted to read or write protected memory. This is often an indication that other memory is corrupt", on the line cmd.ExecuteNonQuery();
Here is the code:
string sql = "select rowid, first_name, last_name, salary from employees where employee_id = :1" +
"select country_id, country_name, region_id from countries where country_id = :2";
string constr = "User Id=hr;Password=Parola_007;Data Source=ORCL;Pooling=false";
con = new OracleConnection(constr);
con.Open();
OracleCommand cmd = new OracleCommand(sql, con);
OracleParameter p_id = new OracleParameter();
p_id.OracleDbType = OracleDbType.Decimal;
p_id.Value = 149;
OracleParameter p_id2 = new OracleParameter();
p_id2.OracleDbType = OracleDbType.Varchar2;
p_id2.Value = "BE";
cmd.BindByName = true;
cmd.Parameters.Add(p_id);
cmd.Parameters.Add(p_id2);
OracleDependency dep = new OracleDependency(cmd);
cmd.Notification.IsNotifiedOnce = false;
dep.OnChange += new OnChangeEventHandler(OnDatabaseNotification);
cmd.ExecuteNonQuery();
public static void OnDatabaseNotification(object src, OracleNotificationEventArgs args)
{
string sql = "select rowid, first_name, last_name, salary from employees where rowid = :1" +
"select rowid, country_id, country_name, region from countries where rowid = :2";
OracleParameter p_rowid = new OracleParameter();
p_rowid.Value = args.Details.Rows[0]["rowid"];
OracleParameter p_rowid2 = new OracleParameter();
p_rowid2.Value = args.Details.Rows[1]["rowid"];
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = sql;
cmd.BindByName = true;
cmd.Parameters.Add(p_rowid);
cmd.Parameters.Add(p_rowid2);
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
Console.WriteLine();
Console.WriteLine("Database Change Notification received!");
DataTable changeDetails = args.Details;
Console.WriteLine("Resource {0} has changed.", changeDetails.Rows[0]["ResourceName"]);
Console.WriteLine("Resource {1} has changed.", changeDetails.Rows[1]["ResourceName"]);
dr.Dispose();
cmd.Dispose();
p_rowid.Dispose();
}
Am I doing something wrong?
Thanks.
1: you cannot do 2 sql in 1 command.
2: You can use the table trigger in oracle to check the changed table data. All changes should be logged in a table and only need to be query from that table.
sorry for my english
I'm trying to make a query when the user clicks the End Shift button to get the total sales of the day right away without entering the date
I can't figure out how can that be possible, I'm currently using this code for it, which he has to choose 2 dates.
I tried with 1 datetimepicker but I never get a result
can it be done without the user choosing the date?
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
{
conn.Open();
string query = #"select SUM(SQuantity) AS 'Total' From Sales where Sdate = #datetime";
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(query, conn);
cmd.Parameters.Add("#datetime", System.Data.OleDb.OleDbType.Date).Value = dateTimePicker1.Value;
cmd.Parameters.Add("#datetime2", System.Data.OleDb.OleDbType.Date).Value = dateTimePicker2.Value;
cmd.ExecuteNonQuery();
string result = cmd.ExecuteScalar().ToString();
textBox1.Text = #result;
}
Try this
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
{
conn.Open();
string query = #"select SUM(SQuantity) From Sales where Sdate = #datetime";
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(query, conn);
cmd.Parameters.Add("#datetime", System.Data.OleDb.OleDbType.Date).Value = dateTimePicker1.Value.ToShortDateString();
//cmd.Parameters.Add("#datetime2", System.Data.OleDb.OleDbType.Date).Value = dateTimePicker2.Value;
//cmd.ExecuteNonQuery();
//string result = cmd.ExecuteScalar().ToString();
textBox1.Text = cmd.ExecuteScalar().ToString();
}
can it be done without the user choosing the date?
Yes, take a look at the #M.Rezaeyan answer.
Try
SELECT sum(SQuantity) as 'Total' FROM Sales WHERE Sdate = Date()
Final
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
{
conn.Open();
string query = #"select SUM(SQuantity) AS 'Total' From Sales where Sdate = Date()";
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(query, conn);
textBox1.Text = cmd.ExecuteScalar().ToString();
}
I would like to sum the following two columns from my database table and display it in form of a chart. My code below will run correct, but show empty chart result. Please help !
c.Open();
DateTime startDateTime = Convert.ToDateTime(textBox1.Text);
DateTime endDateTime = Convert.ToDateTime(textBox2.Text);
string query = "SELECT * FROM People_Tracking WHERE Enter_Exit_Time BETWEEN #startDateTime AND #endDateTime ;";
SqlCommand cmd = new SqlCommand(query, c);
cmd.Parameters.Add("#startDateTime", SqlDbType.DateTime).Value = startDateTime;
cmd.Parameters.Add("#endDateTime", SqlDbType.DateTime).Value = endDateTime;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable t = new DataTable();
adapter.Fill(t);
dataGridView1.DataSource = t;
string query1 = "SELECT Sum(Number_of_Enterance) FROM People_Tracking ;";
string query2 = "SELECT Sum(Number_of_Exits) FROM People_Tracking ;";
this.chart1.Series["DateTime"].Points.AddXY("Number_of_Enterance", query1);
this.chart1.Series["DateTime"].Points.AddXY("Number_of_Exits", query2);
I want to retrieve the resulting value of a select statement into a string variable. Like this:
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
cmd1.ExecuteNonQuery();
I want to place the selected treatment value into a string variable. How can I do this?
Use ExecuteReader() and not ExecuteNonQuery(). ExecuteNonQuery() returns only the number of rows affected.
try
{
SqlDataReader dr = cmd1.ExecuteReader();
}
catch (SqlException oError)
{
}
while(dr.Read())
{
string treatment = dr[0].ToString();
}
Or better, use a using statement for it.
using(SqlDataReader dr = cmd1.ExecuteReader())
{
while(dr.Read())
{
string treatment = dr[0].ToString();
}
}
But if your SqlCommand returns only 1 column, you can use the ExecuteScalar() method. It returns first column of the first row as follows:-
cmd.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
string str = Convert.ToString(cmd.ExecuteScalar());
Also you can open your code to SQL Injection. Always use parameterized queries. Jeff has a cool blog article called Give me parameterized SQL, or give me death. Please read it carefully. Also read DotNetPerl SqlParameter article. SQL Injection very important when you are working queries.
Execute Scalar: Getting Single Value from the Database method to retrieve a single value (for example, an aggregate value) from a database.
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
if(cmd.ExecuteScalar()==null)
{
var treatment = cmd.ExecuteScalar();
}
Other Way: ExecuteReader()
try
{
cmd1.CommandText ="SELECT treatment FROM appointment WHERE patientid=#patientID";
cmd1.Parameters.AddWithValue("#patientID", this.DropDownList1.SelectedValue);
conn.Open();
SqlDataReader dr = cmd1.ExecuteReader();
while (dr.Read())
{
int PatientID = int.Parse(dr["treatment"]);
}
reader.Close();
((IDisposable)reader).Dispose();//always good idea to do proper cleanup
}
catch (Exception exc)
{
Response.Write(exc.ToString());
}
the answer:
String res = cmd1.ExecuteScalar();
the remark: use parametrized query to prevent sql injection
There is a lot wrong with your example code.
You have inline sql, which opens you up to sql injection in a major way.
You are using ExecuteNonQuery() which means you get no data back.
string sSQL = "SELECT treatment FROM appointment WHERE patientid = #patientId";
OleDbCommand cmd1 = new OleDbCommand(sSQL, GetConnection()); // This may be slight different based on what `GetConnectionReturns`, just put the connection string in the second parameter.
cmd1.Parameters.AddWithValue("#patientId", text);
SqlDataReader reader = cmd1.ExecuteReader();
string returnValue;
while(reader.Read())
{
returnValue = reader[0].ToString();
}
You just need to use the ExecuteScalar method of the command - this will give you the value at the first row and column of the result set.
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
var result = cmd1.ExecuteScalar();
If your SQL statement returns more than one row/column then you can use ExecuteReader().
You need to use OleDbAdapter.
string connection = "your connection";
string query = "SELECT treatment FROM appointment WHERE patientid = " + text;
OleDbConnection conn = new OleDbConnection(connection);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand(query, conn);
adapter.Fill(dataset);
SqlConnection dbConnect = new SqlConnection("your SQL connection string");
string name = " 'ProjectName' ";
string strPrj = "Select e.type, (e.surname +' '+ e.name) as fulln from dbo.tblEmployees e where id_prj = " + name;
SqlCommand sqlcmd = new SqlCommand(strPrj, dbConnect);
SqlDataAdapter sda = new SqlDataAdapter(strPrj, dbConnect);
ds = new DataSet();
sda.Fill(ds);
dbConnect.Open();
sqlcmd.ExecuteNonQuery();
dbConnect.Close();