Ok, this seems simple but I can't find a solution to save my life. I am trying to do a very simple INSERT query on an Oracle DB. I can log into the DB in TOAD with the same credentials as I use in the code and run the INSERT with no problem, so as near as I can tell there are no permissions issues with the credentials and the query itself is syntacticly correct. When I try to run the below code, it just hangs. No errors or anything. I can see the session pop up in TOAD so as far as I can tell the code establishes the connection with no problem. Here is the code:
String connStr = "Data Source=DB;User id=<USER>;Password=<PASSWORD>;";
String query = "INSERT INTO table (fields) VALUES (values)";
OracleConnection conn = new OracleConnection(connStr);
conn.Open();
OracleCommand cmd = conn.CreateCommand();
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
I have also tried using an ADO connection and got the same result. Any ideas are appreciated.
Have you committed or rolled back the transaction in Toad? Your application could be waiting on a lock held by your session created by Toad.
Have you tried wrapping it in a transaction and explicitly committing after the insert? IIRC, Oracle's default semantics are very transaction-oriented, unlike SQL Server's.
Related
I am using the JOB to continuously watch the table data. Inside the JOB i am calling the SQLCLR SP. SQLCLR SP will run. Before the while loop i will open the SQL connection. Inside for loop i will access the database 1000-10000 times in only one connection. I wont close the DB connection untill my work is done.
SqlConnection connection = null;
try
{
using (connection = new SqlConnection("context connection=true"))
{
connection.Open();
DataTable dt;
SqlDataAdapter adp=new SqlDataAdapter("select * from tableName",CnStr);
DataSet ds=new DataSet();
adp.Fill(ds,"TableName");
dt= ds[0];
//dt.Rows.count may be range from 1000-10000
for(i=0;i<dt.Rows.count;i++)
{
int id = int.Parse(dt.Rows[i][0].ToString());
SqlCommand command = new SqlCommand("select * from table1 where IsParsed=0 and Id=" + id, connection);
SqlDataReader r1 = command.ExecuteReader();
SqlCommand command = new SqlCommand("Insert into table2 (values)", connection);
int r2 = command.ExecuteNonQuery();
//Always get table1 data which has IsParsed=0. Get those rows manipulate those rows data and
// insert into datatable table2 and update those rows to IsParsed=1
SqlCommand command = new SqlCommand("Update table1 set IsParsed=1 where id=#id", connection);
int r3 = command.ExecuteNonQuery();
// Run the Billing Logic here
// Insert into Billing Table
SqlCommand command = new SqlCommand("Insert into Billing(values)", connection);
int r2 = command.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
}
finally
{
connection.close();
}
Is there any problem with this approach let me know? Is there any issue with using the connection like this? Provide proper suggestion..
I gone through the article
better way to Execute multiple commands in single connection
Here I am using the Context Connection and executing the thousands of command in single connection. Is there any consideration of Connection pool in context connection..? How about the performance of single command execution for each connection vs multiple command execution with single connection?
Also I want to know that in both cases like context connection and regular connection yields to same result? because the SP is deployed in DB itself. If I wrong please correct me.
There is no problem in executing large number of queries over a single connection. Any how you are using a SQL CLR Procedure with context connection. As mentioned in MSDN it states that:
using the context connection typically results in better performance and less resource usage. The context connection is an in-process–only connection, so it can contact the server "directly" by bypassing the network protocol and transport layers to send Transact-SQL statements and receive results. The authentication process is bypassed, as well.
Please refer this link for more information on context and regular connection.
No. It is fine to execute a large number of queries over a single connection.
Your code would likely perform worse if you were to open/close a connection to run those three SQL queries for each of those 1000+ rows.
I am getting an error while connecting to the sql from my cs file. I am trying to create CLR functions in c# without using any IDE which is the requirement. I need to access the database to get some value. Following is the code to connect to my database in c#.
using (SqlConnection conn = new SqlConnection("context connection=true"))
{
conn.Open();
SqlCommand cmd = new SqlCommand(
"SELECT COUNT(*) AS 'Order Count' FROM customer_master with (nolock)", conn);
SqlContext.Pipe.ExecuteAndSend(cmd);
return (int)cmd.ExecuteScalar();
}
but I am getting the following error:
"The requested operation requires a SqlClr context, which is only available when running in the Sql Server process". If i use pipe i don't know how to convert that to an int value. Any suggestions please....
As per this Blog post, try it like this, with the SQLConnection not in a using. The SQLCommand is Disposable and should be in a using though.
SqlConnection conn = new SqlConnection("context connection=true") ;
using(SqlCommand cmd = new SqlCommand(
"SELECT COUNT(*) AS 'Order Count' FROM customer_master with (nolock)", conn))
{
conn.Open();
return (int)cmd.ExecuteScalar();
}
I wrote the below first, but I think the above is the answer, I'm leaving struck out in case it is relevant.
A ContextConnection is a connection back down the existing open connection that the SQL calling the CLR function is using.
To use a SQL CLR Function with a ContextConnection you have to call it from inside a SQL Statement.
e.g. (where CLRConvert is my CLR function that connects back to my database and performs a query and converts stuff).
select dbo.CLRConvert(Data) from MyTables;
If you need to call it outside of here, you will need a proper connection string.
I'm trying to insert data into a database. the connection is working fine. However I can't insert data and I have no idea why. The table is just not getting updated.
string ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Kaushalya\\Documents\\NewAgain.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlCommand cmd = new SqlCommand("Insert into Tabel1(name) VALUES (#UserName);",conn);
cmd.Parameters.Add(new SqlParameter("#UserName", Convert.ToInt32(0)));
Connection when tested is working fine. However, I can't do anything with the database.
You need to execute the Command object.
cmd.ExecuteNonQuery();
More info here.
You need to call ExecuteNonQuery() to run the query.
when I run this sql:
insert into table1(ID,Name) values ('10','Saeed');
it seems that the record has been inserted, and if I read the table using (select * from table1) it shows me the inserted record, but after closing the program, it disappears.
it's the code:
string constr="Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|" +
"\\Database1.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into st (ID,Name) values ('10','saeed');", con);
cmd.ExecuteNonQuery();
cmd.Close();
I inserted some records in it manually, and when I read the database, the manually inserted records exist.
It is not a transaction problem wont be solved with a transaction!
The issue sounds like you started a transaction and forgot to commit it. However, if you are using the exact code you posted this is not a transaction problem because you are not using one.
That makes me think there is something funky going on with your connection string.
For kicks and giggles trying changing your connection string to something like this
Server=myServerName\theInstanceName;Database=myDataBase;Trusted_Connection=True;
Guess:
You are working with SQL Server Express and "Database1.mdf" within your project is configured (in properties window) for "Copy to Output Directory" value "Always"
Try to specify: "Initial Catalog=InstanceDB;" as well to make sure it does not create a new db name when you restart the application.
error in your code itself
its
con.Close();
not
cmd.Close();
there is no close method for SqlCommand
I agree with pascal. Sounds like the transaction isn't being committed.
(Edited to provide clearer code block from my Comment below)
con.Open();
trans = con.BeginTransaction();
SqlCommand cmd = new SqlCommand( "insert into st (ID,Name) values ('10','saeed');", con);
cmd.ExecuteNonQuery();
tran.Commit();
I am trying to execute a sql query as another login using the 'Execute As' command. I am using Linq to SQL, so I've generated a Data Context class and I am using the ExecuteQuery method to run the 'Execute As' SQL command. I then call a Linq to SQL command that is successful. However, every subsequent query fails with the following error:
A severe error occurred on the current command. The results, if any, should be discarded.
Here is the code snippet that I have tried:
SummaryDataContext summary = new SummaryDataContext();
summary.ExecuteQuery<CustomPostResult>(#"Execute as Login='Titan\Administrator'");
var test = summary.Customers.First();
var test2 = summary.Products.ToList();
No matter what query I run on the second query I receive the error message from above. Any help would be appreciated.
I managed to get around this issue in my application by executing the query using ADO.NET classes.
SqlCommand cmd = new SqlCommand("EXECUTE AS USER = 'operator'");
cmd.Connection = dc.Connection as SqlConnection;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
// do the rest of the queries using linq to sql
You may have already ruled this out, but one possible work around would be to simply create the data context with a different connection string.
To edit the connection string, you can set the DataContext.Connection.ConnectionString property. I've done it before in the partial method OnCreated(), which gets called when the data context gets created. I haven't tested but I think you could also do:
YourDataContext dc = new YourDataContext();
dc.Connection.ConnectionString = "connection string here";
Here's an article that describes this as well - http://www.mha.dk/post/Setting-DataContext-Connection-String-at-runtime.aspx
I was having a similar issue and by looking at ruskey's answer I was able to Execute as User but noticed that I was getting errors when running other queries after that. It was due to the missing Revert. So for anyone having a similar issue this is how the code looks like.
SqlCommand cmd = new SqlCommand("EXECUTE AS USER = 'domain\\user';");
OSSDBDataContext dc = new OSSDBDataContext();
cmd.Connection = dc.Connection as SqlConnection;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
//Execute stored procedure code goes here
SqlCommand cmd2 = new SqlCommand("REVERT;");
cmd2.Connection = dc.Connection as SqlConnection;
cmd2.ExecuteNonQuery();