I am writing code for a small company that is all about purchase and sell. I wrote C# code with using external database (SQL Server 2014), now it's time to make the exe file of that code.
I tried my best but it doesn't work.
How can I connect SQL Server 2014 database files with my application so that when someone installs it on his computer he also got SQL Server connected with that application?
Hi actually we deploy code as setup file (.msi), you can create setup project using Wix or install-shield ( maybe other too,but these two are most popular and widely used)
You can do database deployment in two ways
1.) you can provide SQL script for generating SQL server and give instruction for generating Database from Script. It is simple and easy to do.
2.) Other way is provide option to create database from setup. It need some work, but it is more good way.
Now come to your question, you can provide some UI in setup that take input from user and connect to appropriate DB. Or create a UI for Updating configurations, and save configuration (connection string ) in some file ( ex: .ini or .config file).
Below are the some URL for creating Setup and connecting to Db using Wix:
WIXDataBase
installing-databases-using-wix
Creating-an-installer-using-Wix
using-wix-to-install-sql-databases-and-execute-sql-scripts
WiX Samples
Ideally you'd have a SQL server set up somewhere. If not you'll have to install sql server. In your app it's just a matter of setting up the connection string and running sql commands against it.
string connectionString = "Data Source=server //rest of connection string"
Then in c# you can do
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("SELECT TOP 100 * FROM SomeTable", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1} {2}",
reader.GetString(0), reader.GetString(1), reader.GetString(2));
}
}
}
GetString can be changed to GetInt or whatever the datatable will be. This should be enough information to get you started. If you know the structure of the database its simple to put the results into your classes for the application.
Related
The following script works within a SQL Server 2014 Management Studio in a Stored Procedure but not when I call the stored proc via a C# app .NET Framework 4.8.
SQL Code:
create proc getData
as
Insert INTO tmpLeaveImport ([CarName], Year, Make , Model)
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.15.0',
'Excel 12.0;Database=E:\Cars\Cars.xlsx',
'SELECT * FROM [Car Report$]')
From C# I get the following error:
System.Data.SqlClient.SqlException: 'Cannot initialize the data source
object of OLE DB provider "Microsoft.ACE.OLEDB.15.0" for linked server
"(null)". OLE DB provider "Microsoft.ACE.OLEDB.15.0" for linked server
"(null)" returned message "Unspecified error".'
When this code is executed in C#:
//Tried the conn strign with Integrated Security=yes and SSPI
string ConnString = #"Data Sournce=MySQLServerDB;Initial Catalog=DBName;Integrated Security=true;";
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "getData";
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
}
conn.Open();
}
Short Version
According to this possibly duplicate question the Excel file may be open. Or this could be a more serious error.
Don't use OPENROWSET to import Excel data into SQL Server. Use a library like ExcelDataReader to read it without using the Access Engine and insert it to the target table with SqlBulkCopy. You'll avoid a lot of pain.
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
using (var bcp = new SqlBulkCopy(connString))
{
bcp.DestinationTableName ="SomeTable";
bcp.WriteToServer(reader);
}
}
}
Long Version
In both cases, the stored procedure runs on SQL Server, not on the client. SSMS is just another client as far as SQL Server is concerned. Assuming the same server is used in both cases, what's different is that the account that executes the stored procedure is different in each case.
With SSMS, it's the developer's account which quite often has sysadmin privileges on the server. With C#, the account may be the end user's, or the application pool account that runs a web site, which has very restricted privileges. SQL Server's default service account is a restricted account too.
This matters because the Access Engine is a COM component. To use it, applications need to look it up in the registry, which requires its own permissions. If you search SO for the error you got you'll see questions where the choice of service account affected whether Access Engine can be used or not. In other cases, the file was open.
Another potential problem is that ACE must target the same architecture as any previous Office components installed on a machine. If you have a x86 Office application, you can only install the x86 version of ACE. That's because you can't use COM component created for one architecture from a process that targets another one.
This also means you can't use an x86 ACE in a x64 installation of SQL Server, which is the most common installation option in the last 10+ years.
I created a new database using SQL Server 2008 R2 by using the Management Studio. The connection says (local) and I am using Windows Authentication (though I installed with mixed mode).
My questions are:
How do I connect to the DB via my C# application -
The only time I ever have done this before I just used VS Menu > Tools > Connect to DB and the drop down saw my database and connected, then right clicked on it and grabbed the connection string for use in connecting. However I'm thinking because its (local) I don't have that option.
As per Q#1 I am assuming the database file is being stored somewhere locally - I am wondering how to find that location and how I can include it with my application
Edit** Per comment: VSMenu-> View-> Server Explorer and then use add connection to connect to your local SQL Server instance and then use the database you created from the databases dropdown, and from advance settings copy the connection string created by the connection dialog
This is what I am looking for but I am missing the step during "add connection" where do I find my SQL Server I created locally? As mentioned before I have no idea where it is stored or how to find it
MSDN has an example in the SQLConnection documentation
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(queryString, connection))
{
command.Connection.Open();
command.ExecuteNonQuery();
}
You can then optionally use a SqlDataAdapter.
You need to use ADO.NET, which is comprised of a connection object (SqlConnection), command object (SqlCommand), parameters objects (SqlParameter) and data sets (DataSet) or data readers (SqlDataReader).
Read A Beginner's Tutorial for Understanding ADO.NET.
I have this code snippet that creates backup of db:
try
{
string connStr = "<valid connection string>";
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
string sqlStmt = String.Format("BACKUP DATABASE InventoryDB TO DISK='{0}'",
DBBackupSaveFileDialog.FileName);
using (SqlCommand bu2 = new SqlCommand(sqlStmt, conn))
{
bu2.ExecuteNonQuery();
}
...
problem is that it works fine on developer pc but when i try on different machine it will give this error
Cannot open backup device 'C:\User\Saleh\Documents\12.bak'. Operating system error 5 (failed to rerieve text for this error. Reason: 15105).
You need to make sure the SQL Server service account has write access to C:\Users\Saleh\
First, see what account SQL Server is running as. Control Panel > Administrative Tools > Services, right-click the relevant SQL Server service, hit Properties, and see the account listed on the Log On tab. Now go to Windows Explorer, right-click the folder, hit Properties, and on the Security tab, you can add this user account to the list, and make sure they have write access. If you have further problems with this, your question should probably to to superuser.com as it's becoming a Windows / permissions problem, not a programming one.
Better yet, stop running backups to user folders - use SQL Server's backup folder, which SQL Server already has permissions to write to. If you need to move it later, do that separately.
I'm making an ASP.net with c# webapp using VS 2008, and I added a new sql database item to my project. I added tables to the databse. In the database explorer the test connection works. I guess I have two questions. One:In the application, how does one connect to the database using a connection string? or what connection string should I use? Second: How do I add a username and password to the database?
Right now I'm using this connection string in the web.config file, but when I run the app it times out and says it can't make a connection. The error is on the conn.open line.
add name="ReportsConnectionString" connectionString="Data Source=(local); Initial Catalog=REPORTS;Integrated Security=True" providerName="System.Data.SqlClient"
I have this code in one of my page's codebehind.
string sqlquery = "SELECT * FROM reportitems";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ReportsConnectionString"].ConnectionString))
{
conn.Open();
using (SqlCommand comm = new SqlCommand(sqlquery, conn))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(comm))
{
DataSet ds = new DataSet();
adapter.Fill(ds, "reportitems");
DataRowCollection dra = ds.Tables["reportitems"].Rows;
foreach (DataRow dr in dra)
{
string DRZ = dr[0].ToString();
//more stuff here
}
}
}
}
Usually SqlServer Express is reachable on your local PC using this syntax for the Data Source parameter yourpcname\SQLEXPRESS. To be sure start Management Studio and look at the Server Name request.
For the security part of your question, I suppose that you don't want the Integrated Security option (Windows User), but you want a SQLServer user. In this case you could use the User ID and Password parameters for the connection string:
Data Source=MYPC\SQLEXPRESS;Initial Catalog=REPORTS;User Id=MYNAME;Password=MYPASS;
However, this works only after you have added this user to the SQLServer.
You could use the interface of Management Studio app or you could execute a script like this
USE [master]
GO
CREATE LOGIN [MYNAME] WITH PASSWORD=N'MYPASS', DEFAULT_DATABASE=[master]
GO
USE [REPORTS]
GO
CREATE USER [MYNAME] FOR LOGIN [MYNAME]
GO
The Integrated Security=True part of the connectionstring means that the server will use the credentials of the app pool running the site, and you don't need to specify username or password. The app pool identiy will, however, need to have access to your database.
Visit http://www.connectionstrings.com/ for a good primer on various ways to set the connection string for various applications. That'll show you why (local) didn't work but .\SQLEXPRESS did and how to add username and password to it. Here's an example lifted from http://www.connectionstrings.com/sql-server-2008
Data Source=myServerAddress;Initial Catalog=myDataBase;User
Id=myUsername;Password=myPassword;
As others have said, you need a SqlExpress engine running as .mdf is not a flat file. It is a SQL server express database file and you need to connect to it.
But what have not said is that a Database in your App_Data folder needs to be attached to the SqlServer instance. This step is only done once in the first connection.
In http://www.connectionstrings.com/sql-server-2008 you will find an example in the "Attach a database file, located in the data directory, on connect to a local SQL Server Express instance" section that looks like this:
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
Also you can read this: http://msdn.microsoft.com/en-us/library/ms247257.aspx
I believe that you will need to run some scripts and stuff like that to create a user and assign permissions to this user in this database, and then change the connection string (once the database attached), so I don't see a point in having the database in the App_Data folder. I believe it should be better if since the beginning you create your database using the SqlServer tools and connect to it from your application.
Context
My appliction uses an SQL database from which it reads my datatables at start of my application. If the application would fail to connect to the SQL DB, I have a local Ms Access .MDB file. I have a separate thread that checks if the local database is outdated.
I have a DataTable which I obtain from my SQL connection --> Verified and working
I can connect to my Access database locally and read from it --> Verified and working
Issue/Question
I'm trying to update my local database by updating it with the DataTable I obtained from my SQL Connection.
public static void UpdateLocalDatabase(string strTableName, OleDbConnection MyConnection, DataTable MyTable)
{
try
{
if (CreateDatabaseConnection() != null)
{
string strQuery = "SELECT * FROM " + strTableName;
OleDbDataAdapter MyAdapter = new OleDbDataAdapter();
OleDbCommandBuilder MyCommandBuilder = new OleDbCommandBuilder(MyAdapter);
MyAdapter.SelectCommand = new OleDbCommand(strQuery, odcConnection);
MyAdapter.UpdateCommand = MyCommandBuilder.GetUpdateCommand();
MyConn.Open();
MyAdapter.Update(MyTable);
MyConn.Close();
}
}
catch { }
}
If I debug this snippet, all variables are what they should be:
strTableName = the correct name for my table
MyConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MyLocation;Persist Security Info=True;JET OLEDB:Database Password=MyPassword;"
MyTable = is the correct table that is also used further on by my application
This process runs through without an error and without using the catch but it does not touch my database, it just doesn't do a thing.
Am I dropping the ball here or just missing the obvious, I have no idea but I browsed many articles and apart for showing the MyAdapter.Update(), there doesn't seem to be much more to it.
Any help is welcome.
Thanks,
Kevin
Does your backup database have to be in access? because if you used SQL Compact Edition it'd be much easier to copy between the two?
Yes, it would either mean attaching it with your installer or just ensuring that all client machines have it pre-installed, it is free however.
if this is an issue then all you need to do (I think, not done it myself)
would be to go to your installer projects properties, click prerequisites and then tick SQL compact so that it will be installed before your application can be used, iv done this before with other frameworks and it just pops up a box with the install shield asking whether they want to download the necessary software and its just one click then it should be done for them.
Do you need a hand on using the compact database also?
One negative by the way is it does lack some higher end features but shouldn't affect average database work
EDIT
if you will be using sql CE you can easily make the databse in VS by clicking data and new data source then following the steps making sure to put sql CE when asked
if it works, you'll end up with an .sdf database
I provided a code snippet that fixed the issue on my related question here: Export SQL DataBase to WinForm DataSet and then to MDB Database using DataSet