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.
Related
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).
I have a T-SQL script to create a Database. I need to create this database runtime. When the application is Running.
What Connection String do I use?
How do I connect to the server and Create the Database? I am connecting to the server as a Network user. I am not using User "sa" I have a user "DBCreator"
My application is in C#.
I have this Script in T-SQL:
USE [master]
GO
CREATE DATABASE [XYZ]
-- Table Creation Code etc.
You can have two connection strings. One for master database to issue the CREATE DATABASE ... statement and another one for database created.
// You can use replace windows authentication with any user credentials who has proper permissions.
using (SqlConnection connection = new SqlConnection(#"server=(local);database=master;Integrated Security=SSPI"))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "CREATE DATABASE [XYZ]";
command.ExecuteNonQuery();
}
}
// Quering the XYZ database created
using (SqlConnection connection = new SqlConnection(#"server=(local);database=XYZ;Integrated Security=SSPI"))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "select * from sys.objects";
...
}
}
You can use the SMO objects to do that. I don't think i should explain what is already explained in details in a very good tutorial here
Definitely use SMO its intended to do everything that SSMS can do, and more! it actually has a command called Database.Create(), follow this MSDN page
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 have installed SQLite and am using the wrapper from: http://sqlite.phxsoftware.com/
I have created my database and table in the server explorer in VS2010 but when I create the connection, I don't understand what to do from there and how to get it to work.
Can someone provide code examples on how to connect to a db, get a table, insert data into the table and select data from a table and output it.
I would really appreciate it.
Thanks
Server Explorer is overkill, SQLite is meant to be simple and light. Just use plain code as follows.
SQLiteConnection connection = new SQLiteConnection("Data source=PATH_TO_YOUR_DB;Version=3");
connection.Open();
SQLiteCommand command = connection.CreateCommand();
command.CommandText = "insert into something values (1,2,3)";
command.ExecuteNonQuery();
connection.Close();
Hope it helps.
OK here is what I did (assuming that you have that s**t installed):
1.-right click on server explorer
2.-then click on add conection
3.-on data source click Change then select sqlite
4.-fill out da details
5.-you are done... you can now add datasets....
How can I get a DataSet with all the data from a SQL Express server using C#?
Thanks
edit: To clarify, I do want all the data from every table. The reason for this, is that it is a relatively small database. Previously I'd been storing all three tables in an XML file using DataSet's abilities. However, I want to migrate it to a database.
You can use the GetSchema method to get all the tables in the database and then use a data adapter to fill a dataset. Something like this (I don't know if it compiles, I just paste some code and change it a bit):
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
DataTable tables = null;
DataSet database = new DataSet();
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=True";
string[] restrictions = new string[4];
// Catalog
restrictions[0] = "Northwind";
// Owner
restrictions[1] = "dbo";
// Table - We want all, so null
restrictions[2] = null;
// Table Type - Only tables and not views
restrictions[3] = "BASE TABLE";
connection.Open();
// Here is my list of tables
tables = connection.GetSchema("Tables", restrictions);
// fill the dataset with the table data
foreach (DataRow table in tables.Rows)
{
string tableName = table["TABLE_NAME"].ToString();
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand command = factory.CreateCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "select * from [" + tableName + "]";
adapter.SelectCommand = command;
adapter.Fill(database, tableName);
}
}
EDIT:
Now I refactored it a bit and now it's working as it should. The use of DbConnection and DbProviderFactories is for database engine abstraction, I recommend using it so you can change the database engine changing this line and the connection string:
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OracleClient");
The GetSchema method will retrive all tables from your database to a DataTable and then we get all the data from each table to the DataSet using the DataAdapter.
I think you need to narrow down the question somewhat... All the data? You mean, all the data in every table in every database? Well, the only answer to that is, a lot of code.
To connect to and talk to a SQL Server Express database engine, use the classes in the System.Data.SqlClient namespace, namely:
SqlConnection: Connect to the database
SqlCommand: Talk to the database
SqlDataReader: Iterate over data retrieved from the database
You can check the MSDN pages for all of these classes by clicking on the links above.
Here are some overview-links with more information:
CodeProject: Beginners guide to accessing SQL Server through C#
DevHood: Accessing SQL Server Data in C# with ADO.NET
Note that by and large, you use a SQL Server Express database engine the same way as the full SQL Server product, the difference is more in the tools you get with it, and some limitations in the express engine. Other than that you can just use the classes and language that you would use for a normal SQL Server database engine installation.
If this post didn't answer your question, please elaborate, and you have a higher chance of getting the answer you seek.
This can be done by using dataAdapter class.