How to execute oracle multiple queries in C# [duplicate] - c#

I am using visual studio 2013 and oracle database.I want execute multiple create table queries at once in single oraclecommand is it possible ? I am trying following but not working
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = "create table test(name varchar2(50) not null)"+"create table test2(name varchar2(50) not null)";
//+ "create table test3(name varchar2(50) not null)"+"create table test3(name varchar2(50) not null)";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
Got error at cmd.ExecuteNonQuery();

In order to execute more than one command put them in begin ... end; block.
And for DDL statements (like create table) run them with execute immediate. This code worked for me:
OracleConnection con = new OracleConnection(connectionString);
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText =
"begin " +
" execute immediate 'create table test1(name varchar2(50) not null)';" +
" execute immediate 'create table test2(name varchar2(50) not null)';" +
"end;";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
More info: Executing SQL Scripts with Oracle.ODP

Have you tried
cmd.CommandText = "create table test(name varchar2(50) not null);"+"create table test2(name varchar2(50) not null);";

Related

INSERT INTO Table (Column) VALUE (email)

I want to insert email in Table with only one column. I tried on 2 way. First time I tried with commandText and second time I tried with parapeters. But the both solution give me the same error.
System.Data.OleDb.OleDbException: 'Syntax error in INSERT INTO statement.'
I don't see any error in INSERT STATEMENT. Maybe the problem is in TABLE?
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT COUNT (email) FROM [User] WHERE [email] LIKE '" + userEmail + "';";
conn.Open();
int count = Convert.ToInt32(cmd.ExecuteScalar()); // This passed
if (count == 0)
{
string query = #"INSERT INTO User (email) VALUES (#email)";
string cmdText= #"INSERT INTO User (email) VALUES ('"+userEmail+"')";
OleDbCommand command = new OleDbCommand(cmdText, conn);
// command.Parameters.AddWithValue("#email", "userEmail");
// command.CommandText = query;
command.ExecuteNonQuery(); // I GOT ERROR HERE
}
conn.Close();
}
User is a keyword. You should INSERT INTO [USER] instead
string cmdText= #"INSERT INTO User (email)) VALUES ('"+userEmail+"')";
you have one ')' too many after (email)

SQL Server : data not being inserted

I am writing a sample application to insert data into a SQL Server database using C#. Data is not persisting in the database.
Below is my code:
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "Insert into Record (ID,Name) values ('" + txtId.Text + "' , '" + txtName.Text + "')";
cmd.ExecuteNonQuery();
//cmd.Clone();
conn.Close();
The values are not persisted. There is no error when I insert the values. When I changed my command to:
"Insert into Database.dbo.Record (ID,Name) values ('"
it throws an exception:
Incorrect syntax near the keyword 'Database'.
Why is my SQL Server database not being updated?
Your code as is, is possibly open to SQL injection - you should use parameters.
Also check the table names and primary keys, e.g. if ID is an Identity column it is automatically generated when you insert, so then you'll just INSERT INTO Record (Name) VALUES ('Bob')
Otherwise if ID is a primary key you'll likely have to check you are not trying to insert duplicates.
Please use parameters! (adjust the SqlDbType's if needed)
You should also use a using statement over the connection to properly dispose resources, and ideally use a transaction for updates:
string sqlQuery = "INSERT INTO Record (ID, Name) VALUES (#id, #name); ";
using (SqlConnection conn = new SqlConnection(connectionString)) {
conn.Open();
SqlTransaction tran = conn.BeginTransaction();
try {
SqlCommand command = new SqlCommand(sqlQuery, conn, tran);
SqlParameter in1 = command.Parameters.Add("#id", SqlDbType.NVarChar);
in1.Value = txtId.Text;
SqlParameter in2 = command.Parameters.Add("#name", SqlDbType.NVarChar);
in1.Value = txtName.Text;
command.ExecuteNonQuery();
tran.Commit();
} catch (Exception ex) {
tran.Rollback();
//...
}
}

Having some trouble using scope identity

I have two tables, one containing names, and one containing rates and other data that is lined to each name. After I insert a new name into table A, I want to get the newly auto generated PK to now use to insert into my other table B with rates.
How can I do this? I read about scope_identity online but I'm not sure how to use it.
This is what I have so far:
SqlConnection con = new SqlConnection(pubvar.x);
SqlCommand command = con.CreateCommand();
command.CommandText ="Insert into A values('" +Name + "')";
SqlCommand command2 = con.CreateCommand();
command2.CommandText = "Insert into B values(....)";
SELECT SCOPE_IDENTITY();
con.Open();
command.ExecuteNonQuery();
con.Close();
Considering the case you've described, I don't see any need to return the identity from the database. You can simply issue both statements in one command:
using (var cnx = new SqlConnection(pubvar.x))
using (var cmd = new SqlCommand
{
Connection = cnx,
CommandText = #"
insert into A (Name) values (#name)
insert into B (A_ID, Rate) values (scope_identity(), #rate)
",
Parameters =
{
new SqlParameter("#name", name),
new SqlParameter("#rate", .5m) //sample rate
}
})
{
cnx.Open();
cmd.ExecuteNonQuery();
}

Inserting NULL values into mdf table in Windows Forms

I cannot figure out what I am doing wrong here, in the debugger when I set breakpoints the strings all have string values in them, but when it comes time to insert them into the table, nothing gets put in.
the table is defined as follows
CREATE TABLE [dbo].[tblMissEvents] (
[EventID] INT IDENTITY (1, 1) NOT NULL,
[EventTime] NVARCHAR (MAX) NULL,
[MIS_Event_Action] VARCHAR (50) NULL,
[Bogey_Type] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([EventID] ASC)
);
my code:
string date = DateTime.Now.ToString();
string MISaction = text1.Text;
string BogeyType = text2.Text;
try
{
con = new SqlConnection();
con.ConnectionString =
#"data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\MissileEvents.mdf;integrated security=True;MultipleActiveResultSets=True;Connect Timeout=30";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"INSERT into tblMissEvents (EventTime, MIS_Event_Action, Bogey_Type) Values (#date, #MISaction, #BogeyType)";
cmd.Parameters.AddWithValue("#date", date);
cmd.Parameters.AddWithValue("#MISaction", MISaction);
cmd.Parameters.AddWithValue("#BogeyType", BogeyType);
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
con.Close();
Any thoughts?? I don't get an exception, just no entry into my table.
edit for Arshad:
con = new SqlConnection();
con.ConnectionString =
#"data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\MissileEvents.mdf;integrated security=True;MultipleActiveResultSets=True;Connect Timeout=30";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"INSERT into tblMissEvents (MIS_Event_Action, Bogey_Type) Values (#date, #MISaction, #BogeyType)";
cmd.Parameters.AddWithValue("#date", date);
cmd.Parameters.AddWithValue("#MISaction", MISaction);
cmd.Parameters.AddWithValue("#BogeyType", BogeyType);
cmd.Connection = con;
cmd.ExecuteNonQuery();
UPDATE:: The code was fine, it was making a copy of the DB in my bin\Debug directory and thats where all the data was going. Probably something with my connection string setup. Thanks all!
You can pass null value also as :
cmd.CommandText =
"INSERT into tblMissEvents (EventTime, MIS_Event_Action, Bogey_Type)
Values (#eventTime, #MISaction, #BogeyType)";
cmd.Parameters.AddWithValue("#eventTime", DBNull.Value);
cmd.Parameters.AddWithValue("#MISaction", MISaction);
cmd.Parameters.AddWithValue("#BogeyType", BogeyType);
Update 1
cmd.CommandText =
"INSERT into tblMissEvents (EventTime,MIS_Event_Action, Bogey_Type)
Values
(#date, #MISaction, #BogeyType)";
Update 2
int RowUpdated=cmd.ExecuteNonQuery();
MessageBox.Show("Number of row updated"+RowUpdated);

C# Get insert id with Auto Increment

I am using this method to insert a row into a table:
MySqlConnection connect = new MySqlConnection(connectionStringMySql);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.Connection.Open();
string commandLine = #"INSERT INTO Wanted (clientid,userid,startdate,enddate) VALUES" +
"(#clientid, #userid, #startdate, #enddate);";
cmd.CommandText = commandLine;
cmd.Parameters.AddWithValue("#clientid", userId);
cmd.Parameters.AddWithValue("#userid", "");
cmd.Parameters.AddWithValue("#startdate", start);
cmd.Parameters.AddWithValue("#enddate", end);
cmd.ExecuteNonQuery();
cmd.Connection.Close();
I hav also id column that have Auto Increment .
And i want to know if it possible to get the id that is created when i insert a new row.
You can access the MySqlCommand LastInsertedId property.
cmd.ExecuteNonQuery();
long id = cmd.LastInsertedId;
MySqlConnection connect = new MySqlConnection(connectionStringMySql);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.Connection.Open();
string commandLine = #"INSERT INTO Wanted (clientid,userid,startdate,enddate) "
+ "VALUES(#clientid, #userid, #startdate, #enddate);";
cmd.CommandText = commandLine;
cmd.Parameters.AddWithValue("#clientid", userId);
**cmd.Parameters["#clientid"].Direction = ParameterDirection.Output;**
cmd.Parameters.AddWithValue("#userid", "");
cmd.Parameters.AddWithValue("#startdate", start);
cmd.Parameters.AddWithValue("#enddate", end);
cmd.ExecuteNonQuery();
cmd.Connection.Close();
Basically you should add this to end of your CommandText:
SET #newPK = LAST_INSERT_ID();
and add another ADO.NET parameter "newPK". After command is executed it will contain new ID.

Categories

Resources