Hi have this simple ASPX site setup. In the code behind, I'm connecting to an Oracle database, throwing a SELECT query and putting the result to a DataSet that I can then use/display on the website.
The problem: The query should give me result (works fine inside SQLDeveloper), but when I'm filling the DataSet, it gives me 0 rows every time. No Oracle errors show up, connection to the database opens up fine and the query looks correct.
I would have liked to get some kind of an Oracle error, that would have been easier to troubleshoot. I have tried to find a solution online, but haven't found anything that has helped with my problem.
Here is the relevant code I'm using:
using System.Data.OracleClient;
private OracleConnection conn = new OracleConnection();
-- // Below everyting is in the same method
var ds = new DataSet();
-- // conn.ConnectionString is corretly set
conn.Open(); // connection to database is opened
OracleCommand command = conn.CreateCommand();
var sql = "SELECT * FROM someTable"; -- // the SQL query
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
OracleDataAdapter adapter = new OracleDataAdapter(command);
ds.Tables.Clear();
adapter.Fill(ds);
Here the DataSet (ds) should be full, but it's always empty. Any pointers would be most welcome. Please let me know if I'm missing some information.
Related
I know of two ways to display data on a website.
The first is by using adding a DB connection to the Server Explorer and then dragging the table you want to display on the webpage. Visual Studio does all the backend stuff for you.
The second is where you just choose the control you want to use and you hook it up manually through code for it to display the data you want. You do not have to connect to the DB in server explorer. Something like this in code behind:
SqlConnection sqlConnection = new SqlConnection(connString);
SqlCommand command = new SqlCommand("RawToSummary", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#SDate", SqlDbType.Date).Value = MySDate;
command.Parameters.Add("#EDate", SqlDbType.Date).Value = MyEDate;
sqlConnection.Open();
command.ExecuteNonQuery();
sqlConnection.Close();
private DataTable FillData(string connString, SqlCommand cmd)
{
SqlConnection conn = new SqlConnection(connString);
DataTable dt = null;
try
{
cmd.Connection = conn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds, "tableName");
dt = ds.Tables["tableName"];
}
catch (Exception e)
{
WriteLog("Error: " + e);
}
finally
{
conn.Close();
}
return dt;
}
I have 2 questions:
1) What is the second method called? I am trying to learn more about it but need a Google search term for it.
2) What are the pros and cons of each method?
I am using the following: Visual Studio 2010, SQL Server Management Studio 2008
Server Explorer/Database Explorer is the server management console for Visual Studio. Use this window to open data connections and to log on to servers and explore their system services.
With Server Explorer/Database Explorer we can view and retrieve information from all of the databases connected to. like:
List database tables, views, stored procedures, and functions
Expand individual tables to list their columns and triggers
Right-click a table to perform actions, such as showing the table's
data or viewing the table's definition, from its shortcut menu.
Programmatic approach
Second approach is the programmatic approach to perform the DM (data manipulation) and DD (data definition) functions.
Server Explorer/Database Explorer goes through the same course (connecting with database, query tables etc.) but in the background while in programmatic approach we write commands (queries/stored procedures) for the same.
I hope this gives an idea.
I am trying to update my database with the window form I have created, however an error occurred when I execute the code:
An unhandled exception of type 'System.InvalidOperationException'
occurred in System.Data.dll" at comm.ExecuteNonQuery();
Here is the code that I used to connect to my database. Was the code I used to update the database wrong?
string conn=ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
SqlCommand comm = new SqlCommand("UPDATE ExerciseInstruction SET Accumulated_Daily_Sets_Completed = '0' WHERE ExerciseInstructionsID ='" + exerciseInstructionID +"'", connection);
comm.ExecuteNonQuery();
Here is the complete error message :
ExecuteNonQuery requires an open and available Connection. The
connection's current state is closed.
The error message explain all. The command cannot be executed if the code doesn't know how to reach the database. Just a call to connection.Open should fix the problem, however I think you need to use a proper way to execute the query.
This is called Parameterized query. In this way you don't concatenate strings together to form you query text but use parameters to pass values to the database engine and a special formatted string containing the parameters placeholders.
There are two main advantages to do so. It is not possible to target your code with Sql Injection hacks and you don't have to handle quoting around your strings (an infinite source of bugs)
string conn=ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
string cmdText = #"UPDATE ExerciseInstruction
SET Accumulated_Daily_Sets_Completed = 0
WHERE ExerciseInstructionsID =#exid";
using(SqlConnection connection = new SqlConnection(conn))
using(SqlCommand comm = new SqlCommand(cmdText, connection))
{
connection.Open(); // Need this before executing the query
comm.Parameters.Add("#exid", SqlDbType.Int).Value = exerciseInstructionID;
comm.ExecuteNonQuery();
}
I have written a code in ASP.NET to fetch data from Oracle database. The code returns data from locally hosted Oracle DB but when I am pointing towards the remote OracleDB, nothing comes. However, if I run same query on the remote DB using SQL Developer Tool, it works fine.
I have debugged my code for right SQL statement and it is absolutely correct.
Following is my code snippet
using (Oracle.DataAccess.Client.OracleConnection con = new
Oracle.DataAccess.Client.OracleConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["ca_eFormsVSED"].ConnectionString;
con.Open();
// query for fetch username and market
String sql = "a valid query"
Oracle.DataAccess.Client.OracleCommand cmd = new Oracle.DataAccess.Client.OracleCommand(sql, con);
cmd.CommandType = CommandType.Text;
if (con.State == ConnectionState.Open)
{
Oracle.DataAccess.Client.OracleDataReader dr = cmd.ExecuteReader();
}
if (dr.Read())
{
//Do Something
}
}
Please suggest how to make it work.
I got the solution of this problem and it may help some one else. If you are 100% sure that code is correct and current SQL statement returns data from database, then check carefully your database tables have dependency or not. Remove existing tables and import new data again and it works fine for me.
So I'm passing a ClientID to my DB and using that to look up all their details, then I want to use those details to also get all other users closely matching the details. I have all this written but my problem is I want to return the initial user's details also. For example;
Select Details = #UserDetails
from UnregisteredUserTable
where UserId = #UserID
Select BunchOfUsersWithMatchingData
from RegisteredUserTable
where UserDetails like #UserDetails
Obviously I've removed unnecessary info. But as you can see this returns all the data of the matching users but not the initial user's details. Could I use a CTE somehow?
UPDATE
Apologies, no idea my data access mattered. I'm doing pretty much the following atm but can change it no problem.
Dim results = thisObjectContext.MatcherSP(UserID)
For Each obj In results
TableData.Rows.Add(obj.IdNumber, obj.name,
obj.emailaddress1, obj.telephone1, obj.telephone2, obj.address1_line1,
obj.address1_line2)
Next
UPDATE 2
ok so I'm just using the two selects in my SP and it runs fine in SQL Server. But when I try to add it to my dbml in Visual Studio I get a strange error:
Unable to extract stored procedure 'dbo.MySP' because its result set contains muultiple anonymous columns.
Any ideas about that?
Well, this isn't VB code, but I will keep it as simple as possible.
Use a SqlDataAdapter to fill a data set. Results from both your select statements will populate different tables in the the DataSet.
cmd.CommandText = "MatcherSP";
cmd.CommandType = CommandType.StoredProcedure;
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds);
You can then access the data as follows:
tableA = ds.Tables[0];
tableB = ds.Tables[1];
You can use the SqlDataReader's nextresult() method.
using(SqlCommand cmd = new SqlCommand("NameOfSP",c))
{
cmd.CommandType = CommandType.StoredProcedure;
using(SqlDataReader d = cmd.ExecuteReader())
{
while(d.Read()){
//Result data from the first select
}
d.NextResult();
while(d.Read()){
//Result data from the second select
}
}
}
http://twogeeks.mindchronicles.com.dnpserver.com/?p=28&cpage=1#comment-37818
Brilliant article, outlined very clearly exactly what I wanted to do.
Hopefully this is not a ServerFault question...
I'm working forward on migrating a project from storing data in XML Serialization to a MySQL database. I'm using the example provided me from a previous question answered yesterday.
Connecting using phpMyAdmin and MySQL Workbench I've created a Stored Procedure called 'sprocOrderSelectSingleItem'. It seems to work well with MySQL for all I can tell. When I run the SHOW CREATE PROCEDURE sprocOrderSelectSingleItem it returns the following:
CREATE DEFINER=username#% PROCEDURE sprocOrderSelectSingleItem(IN orderID INTEGER)
BEGIN SELECT * FROM tblOrders WHERE ID=orderID; END
My cooperative ASP.NET code goes something like this:
public static Order GetItem(int ID)
{
Order objOrder = null;
using (OdbcConnection objConnection = new OdbcConnection(Utils.ApplicationConfiguration.ConnectionString))
{
OdbcCommand objCommand = new OdbcCommand("sprocOrderSelectSingleItem", objConnection);
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.Parameters.AddWithValue("orderID", ID);
objConnection.Open();
using (OdbcDataReader objReader = objCommand.ExecuteReader())
{
if (objReader.Read())
{
objOrder = FillDataRecord(objReader);
}
objReader.Close();
}
objConnection.Close();
}
return objOrder;
}
When I view the page I get the following error message:
ERROR [42000] [MySQL][ODBC 5.1 Driver][mysqld-5.0.77]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'sprocOrderSelectSingleItem' at line 1
Really not catching on to what could be missing or going wrong. Are there any additional tests I should/could be running to confirm things are working on the MySQL side? Am I missing a step to pass the Stored Procedure call correctly in ASP.NET? The code breaks at the line of:
using (OdbcDataReader objReader = objCommand.ExecuteReader())
Replacing the line of
OdbcCommand objCommand = new OdbcCommand("sprocOrderSelectSingleItem", objConnection);
with this instead
OdbcCommand objCommand = new OdbcCommand("SELECT * FROM tblOrders WHERE ID=" + ID + ";", objConnection);
and everything works as expected.
Thanks for any help you guys can provide.
Your can run an execute on sprocOrderSelectSingleItem in Mysql directly with the ID parameter.
It will show that your StoredProc run correctly.
Here is a sample code in C# that call a stored proc.
OdbcCommand salesCMD = new OdbcCommand("{ CALL SalesByCategory(?) }", nwindConn);
salesCMD.CommandType = CommandType.StoredProcedure;
OdbcParameter myParm = salesCMD.Parameters.Add("#CategoryName", OdbcType.VarChar, 15);
myParm.Value = "Beverages";
OdbcDataReader myReader = salesCMD.ExecuteReader();
Look at the "Call" in the OdbcCommand and the "?" for the parameter that is later supplied with a value.
Can you try something like below:
OdbcCommand cmd = new OdbcCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "{call LoadCustCliOrders(?,?,?,?)}";
cmd.Parameters.Add("CUST_ID",OdbcType.Int);
cmd.Parameters.Add("CLIENT_ID",OdbcType.Int);
cmd.Parameters.Add("DATE_FROM",OdbcType.Date);
cmd.Parameters.Add("DATE_TO",OdbcType.Date);
...
cmd.Parameters["CUST_ID"].Value = _CustId;
cmd.Parameters["CLIENT_ID"].Value = _ClientId;
cmd.Parameters["DATE_FROM"].Value = _DateFrom;
cmd.Parameters["DATE_TO"].Value = _DateTo;
cmd.ExecuteReader
Are you sure that you are using the same username or user with the same access privileges.
I think you need to add the word "CALL" before the stored proc.
It should be CALL sprocOrderSelectSingleItem and try.