I'm trying to use a function via a SQL connection I've done everywhere else in my application (only here it give the error, not the rest of the application). When i searched for what that error code meant the responses i found say it's an error when one can't connect to SQL server? but it doesn't give a solution.
here is my c# code
SqlConnection connection = Database.GetConnection();
DataTable dt = new DataTable("CRC");
SqlCommand cmd = new SqlCommand("SELECT dbo.CalcRentalCharge(#RentalStartDateTime,#RentalEndDateTime,#CarTypeID)", connection);
try
{
connection.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#RentalStartDateTimetext", SqlDbType.DateTime).Value = RentalStartDateTimeBox.Text;
cmd.Parameters.Add("#RentalEndDateTimetext", SqlDbType.DateTime).Value = RentalEndDateTimeBox.Text;
cmd.Parameters.Add("#CarTypeIDtext", SqlDbType.Int).Value = CarTypeID.Text;
connection.Open();
Decimal rentalChange = (Decimal)cmd.ExecuteScalar();
connection.Close();
MessageBox.Show("The rental change is: " + rentalChange.ToString());
if (dr.HasRows)
{
dt.Load(dr);
dataGridView1.DataSource = dt;
}
}
connection.Close();
Can you help me get this FUNCTION to work?
Don't use cmd.ExecuteReader() before adding parameter to command object.
It gives error,
add parameter to command and then cmd.execureReader()
You have a copy/paste error in your variable name:
In the line
cmd.Parameters.Add("#RentalStartDateTimetext", SqlDbType.DateTime).Value = RentalStartDateTimeBox.Text;
the string
RentalStartDateTimetext
needs to be
RentalStartDateTime
In addition to that, because it will pop up as your next error: Your opening and closing of the connection is wrong. Use a using block for the connection as well and open it directly after the start of the block. You don't need to close it manually, the using-block will do that for you.
Related
I want to search data from another SQL Server table (Stocks_Item) to this form (IC) dataGridView1, I can view that data (from Stocks_Item) in this dataGridView1 but I couldn't search. Please help me.
Here is my code:
private void button5_Click(object sender, EventArgs e)
{
conn.Close();
try
{
conn.Open();
SqlCommand selectCommand = new SqlCommand("Select * from Stocks_Item where Stock_No = #Stocks_no", conn);
selectCommand.Parameters.Add(new SqlParameter("Stocks_no", txtsearch_stock_no.Text.ToString()));
SqlDataReader reader = selectCommand.ExecuteReader();
bool rowFound = reader.HasRows;
SqlDataAdapter data = new SqlDataAdapter("Select * from Stocks_Item", conn);
DataTable dt = new DataTable();
data.Fill(dt);
dataGridView1.DataSource = dt;
/* SqlDataAdapter sda;
DataTable dt1;
sda = new SqlDataAdapter("select * FROM colombo_branch ",conn);
dt1 = new DataTable();
sda.Fill(dt1);
dataGridView.DataSource = dt1;*/
MessageBox.Show("Search Found", "Form", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
}
There are many flaws in your code, but the one that is specifically causing your error is because you are not properly closing the SqlDataReader here:
SqlDataReader reader = selectCommand.ExecuteReader();
bool rowFound = reader.HasRows;
As a result, the following line, which also attempts to open a data reader internally throws the exception:
data.Fill(dt);
Normally, you want to use a SqlDataReader inside a using block, something like:
bool rowFound;
using(SqlDataReader reader = selectCommand.ExecuteReader())
{
rowFound = reader.HasRows;
}
... to ensure proper and timely disposal. But in this case, I fail to see the point of that block of code anyways. So why not just remove it altogether?
Additional comments:
Avoid global connections. The fact that the method begins by closing the connection is not a good sign.
Always use using blocks around your SqlConnection, SqlCommand, SqlDataReader, SqlDataAdapter, etc... instances to make sure you don't run into these types of errors or leak resources.
I believe that SqlDataAdapter opens/closes a connection for you. Since you're doing that earlier in your code and using a reader against it, that would be the cause. You could use either the reader or the adapter, but typically wouldn't want to mix them in one connection without properly closing/disposing.
FYI, the MSDN SqlDataAdapter code example utilizes this auto open/close behavior of SqlDataAdapter
I have 2 SqlCommand's, one of them is nested. Why it does not allow me to issue the second SqlCommand (I am using a separate SQLCommand)? It gives an error
There is already an open DataReader associated with this Command which must be closed first.
If I use a separate SqlConnection, it is fine.
SqlCommand cmd = new SqlCommand(qry, cn);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
....
try
{
SqlCommand cmd2 = new SqlCommand(qry2, cn);
cmd2.ExecuteNonQuery();
}
catch (Exception e)
{
// I get this error here
// System.Data; There is already an open DataReader associated with this Command which must be closed first.
}
}
The message is obvious: you can't use same connection for different SqlCommand instance at the same time while DataReader is still open. The SqlDataReader instance explanation already said that:
While the SqlDataReader is being used, the associated SqlConnection is
busy serving the SqlDataReader, and no other operations can be
performed on the SqlConnection other than closing it. This is the case
until the Close method of the SqlDataReader is called. For example,
you cannot retrieve output parameters until after you call Close.
The common solution for this problem is using MultipleActiveResultSets=True on connection string:
<add name="ConnectionName" connectionString="[connection string];MultipleActiveResultSets=True" ... />
Then, use DataTable instead iterating DataReader directly:
var dt = new DataTable();
dt.Load(rd);
foreach (DataRow row in dt.Rows)
{
// other stuff
try
{
SqlCommand cmd2 = new SqlCommand(qry2, cn);
cmd2.ExecuteNonQuery();
}
catch (Exception e)
{
// throw exception
}
}
Additionally, you can put simple check if the previous connection is still open (i.e. serving DataReader) using SqlConnection.State property:
// close if connection still open
if (cn.State == ConnectionState.Open)
{
cn.Close();
}
// open if connection already closed
if (cn.State == ConnectionState.Closed)
{
cn.Open();
}
The simple checks above should be put on any part of code which requesting SqlConnection.
I've ordered SQL Server from Somee. I want to use this SQL Server for my windows form. Somehow, i'm not sure, but whenever i execute the login query what i've found, it will have an unhandled exeption.
private void log_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "workstation id=wbhandler.mssql.somee.com;packet size=4096;user id=acc;pwd=pw;data source=wbhandler.mssql.somee.com;persist security info=False;initial catalog=wbhandler";
con.Open();
string felh = username.Text;
string jelsz = password.Text;
string query = "SELECT * FROM accounts WHERE account=#felhasznalo AND password=#jelszó";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("#felhasznalo", felh));
cmd.Parameters.Add(new SqlParameter("#jelszó", jelsz));
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true )
{
MessageBox.Show("Succes");
}
else
{
MessageBox.Show("Failed");
}
}
I thought that the adress is wrong, but then i found on the website the connection string, and now i don't really know.
I'm thinking what's the problem is.
I have 3 schemes in the sql:
dbo, acc, guest.
I first created a table in dbo, then in acc. Now in both of it. But it doesn't execute the SqlDataReader dr = cmd.ExecuteReader();, sadly. Like i said, it has unhandled exeption. Any solution? Any ideas?
(the acc scheme is an example what i created in somee, so it doesn't exist, it's fake)
I also tried this way:
using (var dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
MessageBox.Show("Sikeres Login!");
}
else
{
MessageBox.Show("Sikertelen Login");
}
}
The problem is always the ExecuteReader()
Try the SqlParameterCollection.AddWithValue Method instead:
cmd.Parameters.AddWithValue("#felhasznalo", felh);
cmd.Parameters.AddWithValue("#jelszó", jelsz);
I will also recommend that you use using statements on your SQL objects to ensure that the unmanaged resources they consume are freed when they are no longer needed. You can read more on the using statement from here.
Another thing that I can suggest is adding Charset=utf8; to your connection string.
I am using Oracle.DataAccess.Client to work with Oracle database in my ASP.Net application. There is no help documentation in MSDN for ODP.Net and Oracle's documentation is really really bad. I am not able find the answer to this simple question.
Is it not possible to execute a simple update statement without having to build a dataset object and updating the dataset?
How to execute an update statement using Oracle ODP.Net in C#?
I will need to check the exact syntax, but here is some quick code off the top of my head
using (OracleConnection con = new OracleConnection(...))
{
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update table set col1 = :param1, col2 = :param2 where key = :keyValue";
cmd.Parameters.AddWithValue("param1", 1);
cmd.Parameters.AddWithValue("param2", "Text data");
cmd.Parameters.AddWithValue("keyValue", "1");
cmd.ExecuteNonQuery();
}
The above creates a command object sets the command up to execute an SQL Update statement, in this example I show one way to setup a parameterized query, you should always go with a parameterized query. Once the command is setup you just call ExecuteNonQuery to actually execute the command.
So after a bit of sleuthing and working this one out for a while, I found that the method I used to add a new parameter to the connection command is as follows. I did not find the method as was stated in the previous post. Mind you I am using a query object that I am passing the values around with.
public Boolean InsertMethod(Query _query)
{
var success = false;
var queryString = string.Format(#"INSERT INTO TABLE(ID, OWNER, TEXT) VALUES (TABLE_SEQ.NEXTVAL,:OWNER, :TEXT)");
try
{
using (OracleConnection con = new OracleConnection(ConString))
{
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = queryString;
cmd.Parameters.Add("OWNER", _query.Owner);
cmd.Parameters.Add("TEXT", _query.Text);
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated > 0) success = true;
}
return success;
}
catch (Exception ex)
{
log.Error(ex);
throw;
}
}
Further to #Chris's answer, here is the documentation page of OracleParameter class which has sample code on using OracleCommand to execute Updates.
EDIT: Here is the entry point for ODP.net documentation.
I'm using an Oracle database(10g) which contains a stored procedure called Foo.
Foo takes 2 datetime as IN parameters and 1 cursor as OUT parameter. I've been trying to make the connection and the query to the database with the OleDbCommand, but since Foo needs a cursor I have no choice but to use a OracleCommand(right?).
When I try to connection to the database I get the following error : "OCIenvCreate has failed return code -1". I've gived the correct permissions to ASPNET user for the oci.dll file so that it can read and execute it. Unfortunately, I still get the same error and I'm lost.
Here is what cause the error
OracleConnectionStringBuilder conBuilder = new OracleConnectionStringBuilder();
conBuilder.DataSource = dataSrc;
conBuilder.UserID = user;
conBuilder.Password = password;
OracleConnection con = new OracleConnection(conBuilder.ConnectionString);
OracleCommand cmd = new OracleCommand("foo", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("this_is_a_cursor", OracleType.Cursor).Direction = ParameterDirection.Output;
con.Open(); // Cause the error at runtime
OracleDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
con.Close();
I've noticed that some other people are having the same problem.
I'm running the application from a Windows Server 2003 Entreprise Edition(I hope this can help).
Thank you.
I'm not quite sure what the exact problem was, but I managed to connect to my database with another provider in the connection string.