Simple Question:
My code looks like this:
var con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=172.20.10.8)(PORT=1521))(CONNECT_DATA=(SID=orcl12c)));");
con.Open();
var adp = new OracleDataAdapter("select * from adr;select * from person;", con);
var ds = new DataSet();
adp.Fill(ds);
Now I would expect to get two tables in the DataSet, but I rather get an exception telling me that the SQL Syntax is not correct... It seems the ; is not recognized that way..? Any Ideas?
Edit #1: Also Adding BEGIN+END; does not work (multiple variations)
Edit #2: Wrapping the selects with execute immediate will run, but won't return a result set.
Solution: Combine the provided answer with Using Dapper with Oracle stored procedures which return cursors and enjoy.
You should write an anonymous pl/sql block that returns ref cursors.
Try this in ADO.NET:
oraConnection = new OracleConnection();
da = new OracleDataAdapter();
ds = new DataSet();
oraConnection.ConnectionString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=172.20.10.8)(PORT=1521))(CONNECT_DATA=(SID=orcl12c)));";
cmdText = "begin open :1 for select * from adr; open :2 for select * from person; end;";
cmd = new OracleCommand();
cmd.CommandText = cmdText;
cmd.Connection = oraConnection;
cmd.CommandType = CommandType.Text;
OracleParameter refcur1 = cmd.Parameters.Add("Refcur", OracleDbType.RefCursor);
refcur1.Direction = ParameterDirection.Output;
OracleParameter refcur2 = cmd.Parameters.Add("Refcur", OracleDbType.RefCursor);
refcur2.Direction = ParameterDirection.Output;
da.SelectCommand = cmd;
da.Fill(ds);
Related
While trying to pass an integer parameter #id to a stored procedure, I get an error da.Fill(ds):
Additional information: Conversion failed when converting the varchar value '#id' to data type int.
I have made sure that integer value is passed and stored procedure contain the correct datatype. What other possibilities are there to rectify this error?
SqlConnection conn = new SqlConnection(cs);
conn.Open();
SqlCommand cmd1 = new SqlCommand("asp_GetTrainingDetail", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#id", id);
SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
da.Fill(ds);
If you know better, do not use AddWithValue() ... it has to "guess" what datatype you have in your DB based on what you put into the command. It is errorprone and causes unneeded conversions to take place.
Also: use using(..) around disposables, especially when using Database-access as it will close your connections even if exceptions arise - not using using might let some connection stay unclosed.
DataSet ds = new DataSet ();
using (var conn = new SqlConnection (cs))
{
using (var cmd1 = new SqlCommand ("asp_GetTrainingDetail", conn))
{
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#id", System.Data.SqlDbType.BigInt).Value = id;
using (var da = new SqlDataAdapter (cmd1))
{
da.Fill (ds);
}
}
}
Read the link in do not use AddWithValue() for more background infos.
Try this...
SqlConnection conn = new SqlConnection(cs);
conn.Open(); SqlCommand cmd1 = new
SqlCommand("asp_GetTrainingDetail", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#id", Int.Parse(id));
SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
da.Fill(ds);
In sql I normally execute my procedure using
exec dbo.usp_FCS 'TIMV','serial'
And I tried something somewhat the same in c# but it seems I got this wrong
using (SqlConnection connection = new SqlConnection("Data Source=;Initial Catalog=;User ID=;Password="))
{
using (SqlCommand cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya" + "'" + MachineName + " ','serial' " , connection))
{
try
{
connection.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
}
catch (SqlException ex)
{
label6.Visible = true;
label6.Text = string.Format("Failed to Access Database!\r\n\r\nError: {0}", ex.Message);
return;
}
}
}
My question is,how can I give those 2 inputs 'TIMV' and 'serial' of my stored procedure using c#?
Edit:
I tried something like this:
using (SqlCommand cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya" , connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", SqlDbType.VarChar).Value = MachineName;
cmd.Parameters.Add("#p2", SqlDbType.VarChar).Value = "serial";
try
{ my code...
And it is still not working
The most correct way to add a parameter to an SqlCommand is through the Add method that allows you to specify the datatype of the parameter and, in case of strings and decimals, the size and the precision of these values. In that way the Database Engine Optimizer can store your query for reuse and be a lot faster the second time you call it. In your case I would write
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#mname", SqlDbType.NVarChar, 20).Value = MachineName;
cmd.Parameters.Add("#serial", SqlDbType.NVarChar, 20).Value = "serial";
This assumes that your stored procedure receives two parameters named EXACTLY #mname and #serial, the type of the parameters is NVarChar and the length expected is 20 char. To give a more precise answer we need to see at least the first lines of the sp.
In your code above also the execution of the command is missing. Just creating the command does nothing until you execute it. Given the presence of an SqlDataAdapter I think you want to fill a DataSet or a DataTable and use this object as DataSource of your grid. Something like this
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
yourDataGrid.DataSource = dt;
And if this is an ASP.NET app, also the DataBind call
yourDataGrid.DataBind();
You use the Parameters collection of the SqlCommand class to send parameters to a stored procedure.
Suppose your parameter names are #p1 and #p2 (Please, for your sake, don't use names like this ever) - your c# code would look like this:
using (var cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya", connection))
{
cmd..CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", SqlDbType.VarChar).Value = MachineName;
cmd.Parameters.Add("#21", SqlDbType.VarChar).Value = "serial";
try
{
// rest of your code goes here....
Note: use the SqlDbType value that fits the parameters data type.
Try this:
DataSet ds = new DataSet("dts");
using (SqlConnection conn = new SqlConnection
("Data Source=;Initial Catalog=;User ID=;Password="))
{
try
{
SqlCommand sqlComm = new SqlCommand("usp_FCS_GetUnitInfo_Takaya",conn);
sqlComm.Parameters.AddWithValue("#p1", MachineName);
sqlComm.Parameters.AddWithValue("#p2", "serial");
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
catch (Exception e)
{
label6.Visible = true;
label6.Text = string.Format
("Failed to Access Database!\r\n\r\nError: {0}", ex.Message);
return;
}
I am trying to put data from a SQL query into a DataGridview, but when I try to run the program I am getting the exception
must declare scalar variable #cathedra
Here is the code:
string connectionString = "user id=bogdan_db; password=1234;server=localhost; Trusted_Connection=yes; database=cafedrascience; connection timeout=30";
string sql = #"select *
from researc r inner join research_cafadra rc on r.id = rc.researc_id
inner join cathedra c on c.id = rc.cafadre_id
where c.name like #Cathedra;";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#Cathedra", SqlDbType.VarChar, 50).Value = comboBox1.Text.ToString();
connection.Open();
command.ExecuteNonQuery();
SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, connectionString); //c.con is the connection string
DataTable table = new DataTable();
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
Where I am mistaking?
The problem is that you're executing the query twice (and also connecting to the database twice). Please delete command.ExecuteNonQuery() and change
SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, connectionString);
to
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
You're adding the parameter to command, which would be correct if you were actually using command. You're not... you call ExecuteNonQuery() and do nothing else with it.
You can remove these lines:
command.Parameters.Add("#Cathedra", SqlDbType.VarChar, 50).Value = comboBox1.Text.ToString();
command.ExecuteNonQuery();
And add this one after creating dataAdapter:
dataAdapter.SelectCommand.Parameters.Add("#Cathedra", SqlDbType.VarChar, 50).Value = comboBox1.Text;
I am trying to use MYSQL select query with c#.
Following query for searching "ID" is working fine:
conn = new MySqlConnection(cs);
conn.Open();
cmd = conn.CreateCommand();
cmd.CommandText = "select * from catalog_product_entity where entity_id = ?Id";
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
cmd.Parameters.Add("?Id", SqlDbType.Text).Value = ProductList[i].ProductId.ToString();
adp.Fill(MagentoProduct);
Now, I want to search exact string value in table. I am using following code and its giving empty result:
My Code:
conn = new MySqlConnection(cs);
conn.Open();
cmd = new MySqlCommand("select * from catalog_category_entity_varchar where value = #Value;", conn);
cmd.Parameters.AddWithValue("#Value", "Storybooks");
MySqlDataReader r = cmd.ExecuteReader();
while (r.Read())
{
log.WriteEntry(r.GetString("value"));
}
This is the problem:
where value = '?cname'
That's specifying ?cname as the literal value you're searching for - when you actually just want the parameter. Remove the quotes and it should be fine:
where value = ?cname
(You should use using statements for the connection and command, mind you...)
You could try SQL Reader
c = new MySqlCommand("select * from catalog_product_entity where column_nam = #Value;", conn);
c.Parameters.AddWithValue("#Value", your string);
MySqlDataReader r = c.ExecuteReader();
and then use Reader methods like reader.GetString("column_name"), ....
With the following code below I have managed to open an Access.mpd database and read rows from the table Saved.
However when I try to change data or add new rows I works fine as long as the program is running but nothing seem to be saved to the access.mdb file.
Update: OleDbCommand apparently cannot simply be modified inside the DataAdapter.
Update: AcceptChanges was by me mistakenly used. If used it tells the affected rows to not be updated.
With these updates the code now works. Still I'm looking for understanding of the issue so explanations why will be appreciated. Also If the fixed code is the way to go.
string connection = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\...\Access.mdb;Persist Security Info=True";
OleDbConnection conn = new OleDbConnection(connection);
OleDbDataAdapter da = new OleDbDataAdapter();
OleDbCommand cmd;
cmd = new OleDbCommand();
cmd.CommandText = "Saved";
cmd.CommandType = CommandType.TableDirect;
cmd.Connection = conn;
da.SelectCommand = cmd;
cmd = new OleDbCommand();
cmd.CommandText = "Saved";
cmd.CommandType = CommandType.TableDirect;
cmd.Connection = conn;
da.InsertCommand = cmd;
cmd = new OleDbCommand();
cmd.CommandText = "Saved";
cmd.CommandType = CommandType.TableDirect;
cmd.Connection = conn;
da.UpdateCommand = cmd;
cmd = new OleDbCommand();
cmd.CommandText = "Saved";
cmd.CommandType = CommandType.TableDirect;
cmd.Connection = conn;
da.DeleteCommand = cmd;
OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
da.InsertCommand = cb.GetInsertCommand();
da.DeleteCommand = cb.GetDeleteCommand();
da.UpdateCommand = cb.GetUpdateCommand();
PbDataSet ds = new PbDataSet();
da.Fill(ds, "Saved");
PbDataSet.SavedDataTable table = ds.Tables["Saved"] as PbDataSet.SavedDataTable;
Here I try to change the data, which works. However it is not saved to file. this now works!
PbDataSet.SavedRow sr = table.Rows[0] as PbDataSet.SavedRow;
sr.berAktiv = true; //Changeing data here
sr.AcceptChanges();
da.Update(table as DataTable);
sr = table.NewSavedRow();
sr.rtAktiv = true;
table.AddSavedRow(sr);
table.AcceptChanges();
da.Update(table as DataTable);
No errors are given anywhere.
How can I fix this, so that the data is saved on the file?
How can I verify, in the running program, that it has really been saved, other than reopen the file?
What I can't see is that you're generating the update statements (or let generate them) anywhere...
//Select data
DataSet dataSet = new DataSet();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, db);
dataAdapter.FillSchema(dataSet, SchemaType.Source);
dataAdapter.Fill(dataSet);
//Make changes to the data in the data set...
//Write changes to the mdb
OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(dataAdapter);
dataAdapter.Update(dataSet);