I have an API in .NET Core 3.1 which insert some data to my databases, the issue is that i had to add a new column to the column where i'm inserting the data, as then the api is called i'm dynamically connect to the database to which i should do the insert, how could i make an altertable if that column not exist and then insert the new item?
Here is the method where i'm inserting the stuff:
public static IActionResult InsertOrder(string piva, string idNegozio, RiepilogoTakeaway ordine, HttpResponse Response) {
string connectionString = getConnectionString(piva);
var query_ordine = #"INSERT INTO `ordini` (`TIPO_OR`, `TAVOLO_OR`, `ORA_OR`, `SENT_OR`, `ID_OR_CFG`, `LOTTERIA_OR`) VALUES (#tipo, #tavolo, NOW(), 0, #id, #lotteria); SELECT LAST_INSERT_ID();";
using var connection = new MySqlConnection(connectionString);
using var cmd = new MySqlCommand(query_ordine, connection);
cmd.Parameters.AddWithValue("#tipo", "STB");
cmd.Parameters.AddWithValue("#tavolo", 0);
cmd.Parameters.AddWithValue("#id", idNegozio);
cmd.Parameters.AddWithValue("#lotteria", ordine.lotteria);
connection.Open();
cmd.Prepare();
string idOrdine = cmd.ExecuteScalar().ToString();
...
}
And that's the alter table i should execute:
ALTER TABLE `ordini`
ADD COLUMN `LOTTERIA_OT` VARCHAR(10) NULL AFTER `ID_OR_CFG`;
Which would be the best way to do it?
Try to deploy the SQL changes before calling it. It's very likely that you'll need higher level of privilege in the database to run the alter or add column, for example, if the SQL user you are using to insert the order doesn't have permissions to change the DB schema.
However, if that is still an option, you will need to execute the SQL schema changeusing command.ExecuteNonQuery().
Possibly worth creating a new method "PrepareSqlTable" so you can call before your query runs. Bear in mind that will impact your application performance/scalability because now we'll be checking that on every single query.
Another alternative, handle this in the catch by looking into the error message and creating it accordingly (provides more performance benefits than the previous option).
Related
I am using EntityFramework and code migrations to keep my Postgres database up to date.
Before deployment on a new environment I would like to make sure the database exists and that the user that will execute queries for the application has enough permissions to do this.
So in short I would like to do the following from my Migrations project before running context.Database.Migrate():
Check whether the database exists
If it doesn't exist create it
Create the user if it doesn't exists
Grant permissions to the user
Run migrations
I have two options (I think):
Run multiple statements at once, keeping the logic inside the query itself and avoid having it in code (C#)
Run statements and deciding in code what to do next.
Option 1 has my preference but when I run the statement checking whether the database exists and create it if it doesn't I get an error: CREATE DATABASE cannot be executed from a function.
The query I'm running looks like this:
DO $$
BEGIN
IF NOT EXISTS(SELECT datname FROM pg_database WHERE datname='database_name') THEN
CREATE DATABASE database_name;
END IF;
END
$$
Option 2 would involve running the statement to check if the database exists with the following code:
using (var conn = new NpgsqlConnection("connection"))
{
conn.Open();
var sql = "SELECT 1 FROM pg_database WHERE datname='database_name'";
var command = new NpgsqlCommand(sql, conn);
var dbExists = command.ExecuteScalar();
if(dbExists == null)
{
command = new NpgsqlCommand("CREATE DATABASE database_name", conn);
command.ExecuteNonQuery();
}
conn.Close();
}
The above code works but I think I prefer option 1.
So I have 2 questions:
How can I fix the CREATE DATABASE cannot be executed from a function error.
Is the second option considered 'wrong'?
I am writing a CLR Update trigger for SQL Server 2008 R2. The trigger needs to write updated values to a table in another database hosted in the same SQL Server instance. When I try to open a connection created with the following connection string from within my trigger I get a "SecurityException":
...new SqlConnection("Data Source=(local);Initial Catalog=[my database];Integrated Security=True")
It is highly desirable that I leave my assembly's permission level as SAFE. I am pretty sure that I'd have to set my assembly's permission level to EXTERNAL_ACCESS to connect to a remote database, but is it possible to connect to another database in the same SQL Server instance with the SAFE permission level?
Thanks.
Yes, it is definitely possible to reference another database in a SQLCLR trigger that resides inside of an Assembly marked as SAFE. The error encountered in the question is due simply to using a regular / external connection string, which requires a PERMISSION_SET of EXTERNAL_ACCESS. But using the in-process / internal connection string of "Context Connection = true;" allows you to run whatever query you want, including a query that references another database via 3-part object name.
I was able to do this with the following code:
Main Table (in TestDB1):
CREATE TABLE dbo.Stuff
(
[Id] INT IDENTITY(1, 1) NOT NULL PRIMARY KEY,
[Something] NVARCHAR(50) NOT NULL
);
Audit Table (in TestDB2):
CREATE TABLE dbo.AuditLog
(
AuditLogID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY,
EventTime DATETIME NOT NULL DEFAULT (GETDATE()),
BeforeValue NVARCHAR(50) NULL,
AfterValue NVARCHAR(50) NULL
);
SQLCLR Trigger on main table (partial code):
string _AuditSQL = #"
INSERT INTO TestDB2.dbo.AuditLog (BeforeValue, AfterValue)
SELECT del.Something, ins.Something
FROM INSERTED ins
FULL OUTER JOIN DELETED del
ON del.Id = ins.Id;
";
SqlConnection _Connection = new SqlConnection("Context Connection = true");
SqlCommand _Command = _Connection.CreateCommand();
_Command.CommandText = _AuditSQL;
try
{
_Connection.Open();
_Command.ExecuteNonQuery();
}
finally
{
_Command.Dispose();
_Connection.Dispose();
}
Test queries:
USE [TestDB1];
SELECT * FROM dbo.Stuff;
---
INSERT INTO dbo.Stuff (Something) VALUES ('qwerty');
INSERT INTO dbo.Stuff (Something) VALUES ('asdf');
SELECT * FROM dbo.Stuff;
SELECT * FROM TestDB2.dbo.AuditLog;
---
UPDATE tab
SET tab.Something = 'dfgdfgdfgdfgdfgdfgd'
FROM dbo.Stuff tab
WHERE tab.Id = 2;
SELECT * FROM dbo.Stuff;
SELECT * FROM TestDB2.dbo.AuditLog;
It looks like it's not possible. However a T-SQL statement can reference another database in the same instance by using [DatabaseName].[dbo].[TableName]. I can do the messy logic in my CLR trigger, then do a final insert into the second database by calling a simple T-SQL stored procedure and passing in parameters.
after connecting to database in C#
string MyConString2 = "SERVER=localhost;" + "user id=mytest;" + "DATABASE=clusters;" + "PASSWORD=mypass;";
I have an algorithm which I need to after each run of algorithm that will fill the database, drop the database "clusters" of mysql manually and again connect to the empty database and run it again,gaining new data in tables
I want to make it automatically how can I drop or empty my database if exists in C# and then run my algorithm?
Here is example code that works and I think this is what you are talking about, if not, feel free to correct me.
using (var connection = new MySqlConnection("server=localhost;user=root;password="))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "drop schema if exists clusters";
command.ExecuteNonQuery();
command = connection.CreateCommand();
command.CommandText = "create schema clusters";
command.ExecuteNonQuery();
}
Prepare sql query for clearing your DB and test it in f.e. MySQL workbench. Following this, just execute it as you would execute regular query against DB in C#. One way is to clear all the tables in your database by using TRUNCATE statement and the second way is to DROP DATABASE and recreate it.
I want to use Microsoft Enterprise library Data Application Block for MS Access database (OLEDB provider)
I want parameter based INSERT functionality with enterprise library (Just like we do for SQL provider with parameter based code like - database.params.Add("#EmpName", this.EmpName);
I want the same thing for MS Access database connection.
Could anybody please let me know How could I do this?
Thanks in advance.
Will this code work?
SirDemon,
Thanks for explanation.. I know everything related to INSERT, Update and Delete for SQL. I want compatible it with MS ACCESS . Okay tell me, is below code will work ?
string query = "INSERT INTO DB (EmployeeID, Name) VALUES (#EmployeeID, #Name)
Database db = DatabaseFactory.CreateDatabase();
DbCommand sqlCommand = db.GetCommandFromText(query);
db.AddInParameter(sqlCommand, "#EmployeeID", this.EmployeeID);
db.AddInParameter(sqlCommand, "#Name", this.Name);
Will this example will work in MS Access database.
You can use OleDbCommand to set your parameters and query, just as you would do with SqlCommand on SQL Provider.
OleDbCommand Overview
OleDbCommand Class Members
To use your example:
string query = "INSERT INTO DB (EmployeeID, Name) VALUES (#EmployeeID, #Name)"
Database db = DatabaseFactory.CreateDatabase();
DbCommand command = db.db.GetSqlStringCommand(query);
db.AddInParameter(command, "#EmployeeID", this.EmployeeID);
db.AddInParameter(command, "#Name", this.Name);
db.ExecuteNonQuery(command);
Should work.
I'm trying to create a windows form application that manipulates data from several tables stored on a SQL server.
What's the best way to store the data locally, while the application is running? I had a previous program that only modified one table, and that was set up to use a datagridview. However, as I don't necessarily want to view all the tables, I am looking for another way to store the data retrieved by the SELECT * FROM ... query.
Is it better to load the tables, make changes within the C# application, and then update the modified tables at the end, or simply perform all operations on the database, remotely (retrieving the tables each time they are needed)?
You can take in one table at a time using a ConnectionString and assign it to a DataTable. You can then make changes to the DataTable in any form you want. Once you are finished making the changes you can commit the changes back to Database by using a DataAdapter.
Here's how to get a table:
DataTable table;
using (SqlDbConnection connection = new SqlDbConnection(connectionString))
{
connection.Open();
using (SqlDbCommand command = new SqlDbCommand(tableName, connection))
{
command.CommandType = CommandType.TableDirect;
SqlDbDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection);
table = new DataTable(tableName);
routeID.Load(dr);
}
}
Here's how to commit the table after changes, make sure to assign your DataTable to a DataSet in order to get the changes for commit:
DataSet dataSet = new DataSet();
dataSet.add(table);
using (var adapter = new SqlDbDataAdapter("SELECT * FROM " + tableName, connection))
{
using (var builder = new SqlDbCommandBuilder(adapter))
{
adapter.Fill(dataSet, tableName);
using (DataSet newSet = dataSet.GetChanges(DataRowState.Added))
{
builder.QuotePrefix = "[";
builder.QuoteSuffix = "]";
adapter.InsertCommand = builder.GetInsertCommand();
adapter.Update(newSet, tableName);
}
}
}
There may be a few miss Types, I didn't compile to check for Errors. Good Luck.
The DataSet object has methods that give you the ability to manipulate data from multiple tables in memory, and then save those changes back to the database. Whether that's a good idea depends on your requirements and data--are there multiple simultaneous users, how do you need to handle conflicting updates, etc. I usually prefer to write changes back to the DB immediately, but then, I usually work in a web app context.