Create .mdf/.sdf database dynamically - c#

How can I with "code" create a new .mdf/.sdf database?
I've tried this:
http://support.microsoft.com/kb/307283
All it does is fail on the ConnectionString. Since I have no connection to a file that exists before I create it, how can I only connect to the SQL Express Server just to create a mdf/sdf database?
I want to be able to just connect to the server and create the file, from there it probably will be easier to create the tables and such.
Any suggestions?

public static void CreateSqlDatabase(string filename)
{
string databaseName = System.IO.Path.GetFileNameWithoutExtension(filename);
using (var connection = new System.Data.SqlClient.SqlConnection(
"Data Source=.\\sqlexpress;Initial Catalog=tempdb; Integrated Security=true;User Instance=True;"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText =
String.Format("CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')", databaseName, filename);
command.ExecuteNonQuery();
command.CommandText =
String.Format("EXEC sp_detach_db '{0}', 'true'", databaseName);
command.ExecuteNonQuery();
}
}
}
Change Catalog=tempdb to Catalog=master, its good worked
Sample use:
var filename = System.IO.Path.Combine("D:\\", "testdb.mdf");
if (!System.IO.File.Exists(filename))
{
CreateSqlDatabase(filename);
}

Regarding .sdf files (SQL Server CE), you can use the SqlCeEngine class to create a new database, as described in this MSDN article.

Create .sdf database
using System.Data.SqlServerCe;
using System.IO;
string folderPath="D:\\Compact_DB"
string connectionString;
string fileName =folderPath+"\\School.sdf";
string password = "12345";
if (File.Exists(fileName))
{
File.Delete(fileName);
}
connectionString = string.Format("DataSource=\"{0}\"; Password='{1}'", fileName, password);
SqlCeEngine obj_ceEngine = new SqlCeEngine(connectionString);
obj_ceEngine.CreateDatabase();

Make sure you have a valid connection string.
The database/catalog that you need must be set to a valid database, usually this can be the "master" which is always available and since you will be using master to create a database.

If you need to create a database from scratch programmatically i normal go into the SQL Server Management Studio and create it through the gui in a first step. But instead of clicking on the OK button in the bottom right, i click on the Script button in the top toolbar. This will give me a complete sql script for creating the database i'd like to have. Then i can alter the script and change the parts i'd like dynamically.

I suppose the problem is in the ConnectionString. It should point to the valid instance of the master db (as in the article you refer to). Make sure it is correct, and it should work.

Use a connectionString with InitialCatalog = master. Since only master has default access to create a database.

Related

SSIS C# Script Task Error

All, I'm using SQL 2014 and Visual Studio 2013.
I have a script task that is not firing. It's being read, but not working. This task creates tables and inserts data into them. I need to do this with a script task as there are 100's of TSV files and the fields may change month to month and it's a pain maintaining individual nodes for each table.
If you look at the code snippet, the message boxes (1) do fire, but the script errors right after - I believe at (2):
The error message is:
I think this error refers to variables that are not accessible in the task or are misspelled, etc. I've checked these Ad nauseam - don't think that's it.
Any help is greatly appreciated. Thank you.
The problem in your code is that you are creating an ADO.NET (C# standard) connection in your script code, but the base of this - DBconn connection manager - is an OLEDB connection manager. These two connections could not be casted into one another.
Suggestions:
If possible, create DBconn connection manager as an ADO.NET. Then your code should work.
In case you have to keep DBconn as an OLEDB connection manager, you have to create a SqlConnection connection in script task based on DBconn. I have done that building connection string for ADO.NET from OLEDB conn string and creating a new SqlConnection with that connection string.
Below is a code sample for function generating Connection String.
using RuntimeWrapper = Microsoft.SqlServer.Dts.Runtime.Wrapper;
using System.Data.OleDb;
using System.Data.SqlClient;
using Microsoft.SqlServer.Dts.Runtime;
static string Get_ManagedConnString(string Src_Name, ConnectionManager CM)
{
if (CM.CreationName != "OLEDB")
throw new Exception(string.Format("Cannot get Conn String from non-OLEDB Conn manager {0}", CM.Name));
RuntimeWrapper.IDTSConnectionManagerDatabaseParameters100 cmParams_Src = CM.InnerObject as RuntimeWrapper.IDTSConnectionManagerDatabaseParameters100;
OleDbConnection oledbConn_Src = cmParams_Src.GetConnectionForSchema() as OleDbConnection;
OleDbConnectionStringBuilder oledbCSBuilder_Src = new OleDbConnectionStringBuilder(oledbConn_Src.ConnectionString);
SqlConnectionStringBuilder sqlCSBuilder_Src = new SqlConnectionStringBuilder();
sqlCSBuilder_Src.DataSource = oledbCSBuilder_Src["Data Source"].ToString();
sqlCSBuilder_Src.InitialCatalog = oledbCSBuilder_Src["Initial Catalog"].ToString();
if (oledbCSBuilder_Src["integrated security"].ToString() == "SSPI")
{
sqlCSBuilder_Src.IntegratedSecurity = true;
}
else
{
sqlCSBuilder_Src.UserID = oledbCSBuilder_Src["User ID"].ToString();
sqlCSBuilder_Src.Password = oledbCSBuilder_Src["Password"].ToString();
}
return sqlCSBuilder_Src.ConnectionString;
}

How to connect to Mysql using C#?

I'm just a beginner in C#. I'm using XAMPP server for MySQL database and Visual C# 2010. Then I have created a database named "testdb" in phpMyAdmin and a table named "login". I have inserted my username and password in the table. I'm doing a simple WinForm login where I made two text boxes for username and password and a button. I have my codes done and there's no compiler error. But I had troubled in one line. It says "Unable to connect to any of the specified MySQL hosts". I added MySql.Data to my references. I want to fetch the data in the database table when I'm going to log in. Then authorize the user or if not matched, it will prompt an error message.
Here is my code:
using MySql.Data.MySqlClient;
public bool Login(string username, string password)
{
MySqlConnection con = new MySqlConnection("host=localhost;username…");
MySqlCommand cmd = new MySqlCommand("SELECT * FROM login WHERE username='" +
username + "' AND password='" + password + "';");
cmd.Connection = con;
con.Open(); // This is the line producing the error.
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read() != false)
{
if (reader.IsDBNull(0) == true)
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return false;
}
else
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return true;
}
}
else
{
return false;
}
}
*I hope for your your feedback. :)
Your immediate problem is probably either an incorrect connection string or the database server is not available. The connection string should be something like this
Server=localhost;Database=testdb;Uid=<username>;Pwd=<password>;
with <username> and <password> replaced with your actual values.
Besides that your code has several issues and you should definitely look into them if this is intended to become production code and probably even if this is just a toy project to learn something. The list is in particular order and may not be comprehensive.
Do not hard code your connection string. Instead move it to a configuration file.
Do not include plain text passwords in configuration files or source code. There are various solutions like windows authentication, certificates or passwords protected by the Windows Data Protection API.
Do not just dispose IDisposable instances by calling IDisposable.Dispose(). Instead use the using statement to release resources even in the case of exceptions.
Do not build SQL statements using string manipulation techniques. Instead use SqlParameter to prevent SQL injection attacks.
Do not store plain text passwords in a database. Instead at least store salted hashes of the passwords and use a slow hash function, not MD5 or a member of the SHA family.
You can use IDbCommand.ExecuteScalar to retrieve a scalar result and avoid using a data reader.
Comparing a boolean value with true or false is redundant and just adds noise to your code. Instead of if (reader.IsDBNull(0) == true) you can just use if (reader.IsDBNull(0)). The same holds for if (reader.Read() != false) what is equivalent to if (reader.Read() == true) and therefore also if (reader.Read()).
Using an O/R mapper like the Entity Framework is usually preferred over interacting with the database on the level of SQL commands.
Try modifying your ConnectionString accordingly to the Standard MySQL ConnectionString:
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Source:
MySQL ConnectionStrings
You can also take a look at the following link, that shows how to connect to a MySQL database using C#:
Creating a Connector/Net Connection String (MYSQL)
Make it simple and sql injection free, and also don't forget to add MySql.Web
in your references since your using XAMPP
public bool Login(string username, string password)
{
DataTable dt = new DataTable();
string config = "server=....";
using (var con = new MySqlConnection { ConnectionString = config })
{
using (var command = new MySqlCommand { Connection = con })
{
con.Open();
command.CommandText = #"SELECT * FROM login WHERE username=#username AND password=#password";
command.Parameters.AddWithValue("#username", username);
command.Parameters.AddWithValue("#password", password);
dt.Load(command.ExecuteReader());
if (dt.Rows.Count > 0)
return true;
else
return false;
} // Close and Dispose command
} // Close and Dispose connection
}

I can't connect to my local SQL Server database

I'm currently learning ADO.NET on C#. I'm learning by a book and tutorials that I found online. I wanted to try some of the samples to get myself familiarized with the whole SQL connnection and command objects and so on. Hence, I tried this:
namespace ConsoleApplication
{
class SqlDemo
{
public void InitConnection ()
{
string connString = #"data source=C:\SQL Server 2000 Sample Databases; database=northwnd; integrated security=SSPI";
SqlConnection conn = null;
try
{
conn = new SqlConnection (connString);
conn.Open ();
Console.WriteLine ("DataBase connection established");
}
catch
{
Console.WriteLine ("DataBase connection not established");
}
finally
{
if (conn != null) conn.Close ();
}
Console.ReadKey (true);
}
static void Main (string[] args)
{
SqlDemo d = new SqlDemo ();
d.InitConnection ();
}
}
}
And no matter how I try, I can connect to the local database. "data source=(local)" don't work.
A couple of things:
1) It looks like you may have a typo in your database name. It should probably be:
database=northwind
2) Your data source should be (local) or . OR you may have an instance installed, in which case you may need to include the instance name as well, such as .\SQLExpress or .\SQLServer.
If you wish to connect to a database file using a path:
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
From: http://www.connectionstrings.com/sql-server-2008
However, you may also need to "Attach" the database to Sql Server. In Management studio, right click the Databases folder and select "Attach..."
If you are using SQL Server 2000, then just put 'local' or simply '.' (exclude the quotes) for the data source. And you have a typo in the database name. It should be 'Northwind'

Querying remote MySql server

I think I have a straight forward question. I'm writing a system that allows users from company A to single sign on to the system and for this I go back to the central database of users at company A and validate the user credentials passed to me.
Currently my implementation involves building up my query using a stringbuilder and then passing the string as command text. My question is; is there a nicer way of doing this. below is my code;
public User LoginSSO(string UserName, Int32 sectorCode)
{
using (OdbcConnection con = new OdbcConnection(ConfigurationManager.ConnectionStrings["ComapnyA"].ConnectionString))
{
con.Open();
StringBuilder sb = new StringBuilder();
sb.AppendLine("Select mx.Id, mx.UserName, mx.firstname,mx.surname,mx.sectorCode,");
sb.AppendLine("mx.deleteFlag, dn.sectorGroupCode, dn.region, dn.district");
sb.AppendLine("from users mx");
sb.AppendLine("Inner Join sector dn on dn.sectorCode = mx.sectorCode");
sb.AppendLine("Where (mx.UserName = '{0}')");
string commandText = string.Format(sb.ToString(), UserName, sectorCode);
using (OdbcCommand comm = new OdbcCommand(commandText, con))
{
using (OdbcDataReader reader = comm.ExecuteReader())
{
if (reader.Read())
{
User user = new User();
user.Id = Convert.ToInt32(reader["Id"]);
user.Username = Convert.ToString(reader["UserName"]);
user.Firstname = Convert.ToString(reader["firstname"]);
user.Surname = Convert.ToString(reader["surname"]);
_dealerGroupCode = Convert.ToString(reader["sectorGroupCode"]);
_region = Convert.ToInt32(reader["region"]);
_district = Convert.ToInt32(reader["district"]);
_dealerCode = dealerCode;
_accessLevel = AccessLevel.Sector;
return user;
}
}
}
}
return null;
}
I don't like the fact that I am building up my sql which is ultimately a static script. Please note that I can't manipulate the remote server in any way or add any stored procedures to it. For the rest of the app I have been using LINQ but I'm assuming that isn't an option.
This is the most low-level way of querying a database with ADO.NET. Open connection, send command, read out results. You should however use parametrized queries instead of String.Format, since that will open up your program to SQL injection. Just consider what would happen if UserName has a ' character in it. The following would be much better:
string sql = #"Select mx.Id, mx.UserName, mx.firstname, mx.surname,
mx.sectorCode, mx.deleteFlag, dn.sectorGroupCode,
dn.region, dn.district
From users mx
Inner Join sector dn on dn.sectorCode = mx.sectorCode
Where (mx.UserName = ?)";
var command = new OleDbCommand(sql);
command.Parameters.AddWithValue(0, UserName);
If you want a higher level interface, look into DataSets/DataAdapters. They aren't as fancy as LINQ, but they'll give you an easy fill/update, and work with any database adapter. If you're using Visual Studio, you even get a visual designer that can generate Typed Datasets in drag-and-drop fashion that'll give you strong-typed accessors for all your data.
You might also want to look into the native MySql connector classes, instead of using ODBC.
You can use ‘sp_addlinkedserver’ system store procedure to link to the remote server server and then fire a query. following is the sample command.:
EXEC sp_addlinkedserver
#server = ‘SourceServer’
, #Srvproduct = ”
, #Provider = ‘SQLNCLI’
, #datasrc = ‘Remote SQL Server instance name’
I suggest you to please refer following link to know about how to run sql query on remote server http://ashishkhandelwal.arkutil.com/sql-server/sql-query-to-the-remote-sql-server/

C# - ExecuteNonQuery() isn't working with SQL Server CE

I got some data inputed by the user that should be added to a Database File (.sdf). I've choose Sql Server CE because this application is quite small, and i didn't saw need to work with a service based database.
Well any way.
Here goes the code:
public class SqlActions
{
string conStr = String.Format("Data Source = " + new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\basedados.sdf");
public SqlCeConnection SQLCEConnect()
{
SqlCeConnection Connection = new SqlCeConnection(conStr);
Connection.Open();
return Connection;
}
public Boolean AdicionarAuditorio(string Nome, int Capacidade)
{
string Query = "INSERT INTO auditorios (nome, capacidade) VALUES (#Nome, #Capacidade)";
using (var SQLCmd = new SqlCeCommand(Query, SQLCEConnect()))
{
SQLCmd.Parameters.AddWithValue("#Nome", Nome);
SQLCmd.Parameters.AddWithValue("#Capacidade", Capacidade);
if (SQLCmd.ExecuteNonQuery() == 1)
{
return true;
} else {
return false;
}
}
}
}
I use the AdicionarAuditorio(string Nome, int Capacidade) function to Insert the data. running ExecuteNonQuery() which is supposed to return the number of affected rows after he as run the query.
So it should return 1 if the query as successful, right?
In the end he returns 1, but if I browser the table data, the data that the query should add isn't there.
So whats wrong here?
NOTE. If your thinking that the
problem is the connection: I can't see
why is the problem once i got some
Select statements that use that
connection function SQLCEConnect()
and they all work pretty well.
Thanks in advance.
Are you sure you are looking at the right file? When you build your app in VS, it copies the SDF file as content to the target folder, so the database in your project will not reflect any updates. Your code is picking up the the file location there.
This is btw not a good practice, because once deployed, the program folders are not writable to your app (could this be the problem - did you already deploy?). Instead, the database file should reside in your appdata folder.
Is it possible that you make the call to AdicionarAuditorio in a TransactionScope without calling transactionScope.Complete()?

Categories

Resources