Having a problems accessing a record in a database using date. I'm doing something wrong here cannot remember if you need to have #. What am I missing?
SqlDataReader MyReader;
SqlConnection Conn;
Conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NoteBook.mdf;Integrated Security=True;User Instance=True");
SqlCommand MyCommand = new SqlCommand();
MyCommand.CommandText = "SELECT Id, Date, Note FROM NoteBook Where Date = #07/04/2011#";//Id = 1"; //; // + Message.Text + "";
MyCommand.CommandType = CommandType.Text;
MyCommand.Connection = Conn;
MyCommand.Connection.Open();
MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);
while (MyReader.Read())
{
TextBox1.Text = (string)MyReader["Note"];
}
The simple adaptation here is single quotes: " ...Where Date = '07/04/2011'"
But the correct thing to do is use a parameter:
MyCommand.CommandText =
"SELECT Id, Date, Note FROM NoteBook Where Date = #MarkDate";
MyCommand.Parameters.AddWithValue("#MarkDate", new DateTime(2011, 7, 4));
That would also solve any notational issues, did you really mean the 4th of July ?
And I would usually include the Time in a Notebook entry (and not call that column Date).
If so, you will need a BETWEEN clause or something.
Related
The query is correct but I want to access the number of rows and show in the front-end page. This code is throwing an error.
protected void Page_Load(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["ConnectionString_cw"].ConnectionString;
OracleCommand cmd = new OracleCommand();
OracleConnection con = new OracleConnection(constr);
con.Open();
cmd.Connection = con;
cmd.CommandText = #"SELECT COUNT (*) from dish";
cmd.CommandType = CommandType.Text;
DataTable dt = new DataTable("Dish");
using (OracleDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows)
{
dt.Load(sdr);
recordMsg.Text = sdr["count(*)"].ToString();
}
}
con.Close();
}
I am using Oracle as database and it is connected already.
As you need a single value there is no use of DataTable and DataReader you can simply use ExcuteScalar of command and get the values.
command.ExecuteScalar();
More Reading https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executescalar?view=dotnet-plat-ext-5.0
or simply
recordMsg.Text=command.ExecuteScalar().ToString();
So the whole code can be written as
string constr = ConfigurationManager.ConnectionStrings["ConnectionString_cw"].ConnectionString;
OracleCommand cmd = new OracleCommand();
OracleConnection con = new OracleConnection(constr);
con.Open();
cmd.Connection = con;
cmd.CommandText = #"SELECT COUNT (*) from dish";
cmd.CommandType = CommandType.Text;
recordMsg.Text=command.ExecuteScalar().ToString();
It is also advisable to use using statement for better use of command and connection.
Use numeric index for the following line of code
recordMsg.Text = sdr["count(*)"].ToString();
Change it to...
recordMsg.Text = sdr[0].ToString();
Or:
Change the two line of code below:
cmd.CommandText = #"SELECT COUNT (*) from dish";
recordMsg.Text = sdr["count(*)"].ToString();
To read
cmd.CommandText = #"SELECT COUNT (*) as rCount from dish";
recordMsg.Text = sdr["rCount"].ToString();
Either option should work well for you.
Note: The numeric index is zero because it's a zero-based index. I trust you understand this
I have question about using why i can not use the same instance of SQLCommand more than one time in the same code?
I tried the code down here and it runs good for the gridview but when i changed the query by using cmd.CommandText() method it keeps saying:
There is already an open DataReader associated with this Command which must be closed first.
This is the code:
string cs = ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "Select top 10 FirstName, LastName, Address, City, State from Customers";
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
cmd.CommandText = "SELECT TOP 10 COUNT(CreditLimit) FROM Customers";
int total = (int)cmd.ExecuteScalar();
TotalCreditLble.Text = "The total Credit :" + total.ToString();
}
catch(Exception exp)
{
Response.Write(exp.Message);
}
finally
{
con.Close();
}
The problem is that you are using the SqlCommand object to generate a DataReader via the command.ExecuteReader() command. While that is open, you can't re-use the command.
This should work:
using (var reader = cmd.ExecuteReader())
{
GridView1.DataSource = reader;
GridView1.DataBind();
}
//now the DataReader is closed/disposed and can re-use command
cmd.CommandText = "SELECT TOP 10 COUNT(CreditLimit) FROM Customers";
int total = (int)cmd.ExecuteScalar();
TotalCreditLble.Text = "The total Credit :" + total.ToString();
There is already an open DataReader associated with this Command which must be closed first.
This is the very reason you don't share a command. Somewhere in your code you did this:
cmd.ExecuteReader();
but you didn't leverage the using statement around the command because you wanted to share it. You can't do that. See, ExecuteReader leaves a connection to the server open while you read one row at a time; however that command is locked now because it's stateful at this point. The proper approach, always, is this:
using (SqlConnection c = new SqlConnection(cString))
{
using (SqlCommand cmd = new SqlCommand(sql, c))
{
// inside of here you can use ExecuteReader
using (SqlDataReader rdr = cmd.ExecuteReader())
{
// use the reader
}
}
}
These are unmanaged resources and need to be handled with care. That's why wrapping them with the using is imperative.
Do not share these objects. Build them, open them, use them, and dispose them.
By leveraging the using you will never have to worry about getting these objects closed and disposed.
Your code, written a little differently:
var cs = ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;
var gridSql = "Select top 10 FirstName, LastName, Address, City, State from Customers";
var cntSql = "SELECT TOP 10 COUNT(CreditLimit) FROM Customers";
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
try
{
using (SqlCommand cmd = new SqlCommand(gridSql, con))
{
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
using (SqlCommand cmd = new SqlCommand(cntSql, con))
{
int total = (int)cmd.ExecuteScalar();
TotalCreditLble.Text = "The total Credit :" + total.ToString();
}
}
catch(Exception exp)
{
Response.Write(exp.Message);
}
}
Thank u quys but for the guys who where talking about using block !
why this code work fine which i seen it on example on a video ! It's the same thing using the same instance of SqlCommand and passing diffrent queries by using the method CommanText with the same instance of SqlCommand and it's execute just fine , this is the code :
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "Delete from tbleProduct where ProductID= 4";
int TotalRowsAffected = cmd.ExecuteNonQuery();
Response.Write("Total rows affected :" + TotalRowsAffected );
cmd.CommandText = "Insert into tbleProduct values (4, 'Calculator', 100, 230)";
TotalRowsAffected = cmd.ExecuteNonQuery();
Response.Write("Total rows affected :" + TotalRowsAffected );
cmd.CommandText = "ypdate tbleProduct set QtyAvailbe = 234 where ProductID = 2";
TotalRowsAffected = cmd.ExecuteNonQuery();
Response.Write("Total rows affected :" + TotalRowsAffected );
}
I am facing error in following Query.According to my knowledge I have written everything perfectly fine. But its giving error that:
"there is an error in update query"
string insert_query = "update aho set read=?,pick=? where Cont_no='" + contract_no + "'";
OleDbCommand ocmd = new OleDbCommand();
ocmd.CommandText = insert_query;
//ocmd.Parameters.AddWithValue("#contrct_no", contract.Text.ToString());
ocmd.Parameters.AddWithValue("#read_val", Convert.ToInt32(read.Text));
ocmd.Parameters.AddWithValue("#pic_val", Convert.ToInt32(pick.Text));
ocmd.Connection = conn;
ocmd.ExecuteNonQuery();
You didn't gave us too much information but..
I think your Cont_no type is some numerical type, not one of the character type. Looks like that's why you get error when you try to add it with ''.
For example like;
Cont_no = '123'
Try this one;
string insert_query = "update aho set [read]=?,pick=? where Cont_no=?";
OleDbCommand ocmd = new OleDbCommand();
ocmd.CommandText = insert_query;
ocmd.Parameters.AddWithValue("#read_val", Convert.ToInt32(read.Text));
ocmd.Parameters.AddWithValue("#pic_val", Convert.ToInt32(pick.Text));
ocmd.Parameters.AddWithValue("#contrct_no", contract_no);
ocmd.Connection = conn;
ocmd.ExecuteNonQuery();
EDIT: HansUp is totally right. Read is a reserved keyword. You should use it with square brackets like [Read] in your query.
In your query string you consider parameters by priority, but when you create them you are giving them a name.
According to http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters.aspx, OleDbCommand does not support named parameters.
Look at this example (source: http://www.java2s.com/Code/CSharp/Database-ADO.net/PassparametertoOleDbCommand.htm):
using System;
using System.Data;
using System.Data.OleDb;
public class Prepare {
public static void Main () {
String connect = "Provider=Microsoft.JET.OLEDB.4.0;data source=.\\Employee.mdb";
OleDbConnection con = new OleDbConnection(connect);
con.Open();
Console.WriteLine("Made the connection to the database");
OleDbCommand cmd1 = con.CreateCommand();
cmd1.CommandText = "SELECT ID FROM Employee "
+ "WHERE id BETWEEN ? AND ?";
OleDbParameter p1 = new OleDbParameter();
OleDbParameter p2 = new OleDbParameter();
cmd1.Parameters.Add(p1);
cmd1.Parameters.Add(p2);
p1.Value = "01";
p2.Value = "03";
OleDbDataReader reader = cmd1.ExecuteReader();
while(reader.Read())
Console.WriteLine("{0}", reader.GetInt32(0));
reader.Close();
con.Close();
}
}
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.
i have database in access with auto increase field (ID).
i insert record like this (in C#)
SQL = "insert into TermNumTbl (DeviceID,IP) values ('" + DeviceID + "','" + DeviceIP + "') ";
OleDbCommand Cmd = new OleDbCommand(SQL, Conn);
Cmd.ExecuteNonQuery();
Cmd.Dispose();
Conn.Close();
how to get the last inserting number ?
i dont want to run new query i know that in sql there is something like SELECT ##IDENTITY
but i dont know how to use it
thanks in advance
More about this : Getting the identity of the most recently added record
The Jet 4.0 provider supports ##Identity
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", Category.Text);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}
I guess you could even write an extension method for OleDbConnection...
public static int GetLatestAutonumber(
this OleDbConnection connection)
{
using (OleDbCommand command = new OleDbCommand("SELECT ##IDENTITY;", connection))
{
return (int)command.ExecuteScalar();
}
}
I like more indicate the type of command
is very similar to the good solution provided by Pranay Rana
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql_Insert;
cmd.ExecuteNonQuery();
cmd.CommandText = sql_obtainID;
resultado = (int)comando.ExecuteScalar();
}
query = "Insert Into jobs (jobname,daterecieved,custid) Values ('" & ProjectNAme & "','" & FormatDateTime(Now, DateFormat.ShortDate) & "'," & Me.CustomerID.EditValue & ");"'Select Scope_Identity()"
' Using cn As New SqlConnection(connect)
Using cmd As New OleDb.OleDbCommand(query, cnPTA)
cmd.Parameters.AddWithValue("#CategoryName", OleDb.OleDbType.Integer)
If cnPTA.State = ConnectionState.Closed Then cnPTA.Open()
ID = cmd.ExecuteNonQuery
End Using
Using #Lee.J.Baxter 's method (Which was great as the others id not work for me!) I escaped the Extension Method and just added it inline within the form itself:
OleDbConnection con = new OleDbConnection(string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}'", DBPath));
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = string.Format("INSERT INTO Tasks (TaskName, Task, CreatedBy, CreatedByEmail, CreatedDate, EmailTo, EmailCC) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", subject, ConvertHtmlToRtf(htmlBody), fromName, fromEmail, sentOn, emailTo, emailCC);
cmd.Connection = con;
cmd.ExecuteScalar();
using (OleDbCommand command = new OleDbCommand("SELECT ##IDENTITY;", con))
{
ReturnIDCast =(int)command.ExecuteScalar();
}
NOTE: In most cases you should use Parameters instead of the string.Format() method I used here. I just did so this time as it was quicker and my insertion values are not coming from a user's input so it should be safe.
Simple,
What we do in excel for copy text in above cell?
Yes, just ctrl+" combination,
and yes, it's work in MS ACCESS also.
You can use above key stroke combination for copy above records field text, just make sure if you have duplicate verification applied or edit field data before move next field.
If you aspects some more validation or any extraordinary then keep searching stack overflow.