So I'm developing a web application where each user has it's own database. What i want is to automate the process of create the user specific database when he registers.
My idea is to create a new empty database with a custom name and then run a pre-made sql script to generate the tables and default values for this database.
Edit
I think I haven't been clear before.
I create the database as follows:
using (var conn = new SqlConnection("data source=MySource; uid=MyUser; pwd=MyPassword;"))
{
using (var cmd = new SqlCommand())
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "Create Database MYNewDB;";
cmd.ExecuteNonQuery();
}
}
Is there a way to (after this) execute the scripts saved in .sql file to create the tables and values for this new data base?
found the solution on this answer.
using (var conn = new SqlConnection("data source=MySource; initial catalog=MYNewDB;persist security info=True;user id=MyUser;password=MyPassword;multipleactiveresultsets=True; "))
{
string script = File.ReadAllText(#"C:\Somewhere\...\script.sql");
// split script on GO command
IEnumerable<string> commandStrings = Regex.Split(script, #"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
conn.Open();
foreach (string commandString in commandStrings)
{
if (commandString.Trim() != "")
{
using (var command = new SqlCommand(commandString, conn))
{
command.ExecuteNonQuery();
}
}
}
conn.Close();
}
Related
I have an SQL script select [master].[dbo].sp_SearchDuplicatedAddress('','','','') that I can invoke successfully from management studio. The function sp_SearchDuplicatedAddress exists in master database and is accessible by the logged user, no problem here. The problem arises when I try to execute that SQL script from ADO.Net I get the following error:
System.Data.SqlClient.SqlException: 'Cannot find either column "master" or the user-defined function or aggregate "master.dbo.sp_SearchDuplicatedAddress", or the name is ambiguous.'
And here's the code of sample app:
var conn = new SqlConnection();
var cmd = conn.CreateCommand();
cmd.CommandText = "select [master].[dbo].sp_SearchDuplicatedAddress('','','','')";
conn.Open();
var outt = cmd.ExecuteScalar();
}
Any idea how can I execute cross database queries from ADO.Net?
No repro for me. Can you modify the below to reproduce the behavior?
using Microsoft.Data.SqlClient;
using System;
namespace SqlClientTest
{
class Program
{
static void Main(string[] args)
{
var constr = "server=localhost;database=master;integrated security=true";
using (var conn = new SqlConnection(constr))
{
var cmd = conn.CreateCommand();
cmd.CommandText = #"
create or alter function dbo.sp_SearchDuplicatedAddress ( #a varchar(20),#b varchar(20),#c varchar(20),#d varchar(20) )
returns int
as
begin
return 3;
end ";
conn.Open();
cmd.ExecuteNonQuery();
}
constr = "server=localhost;database=tempdb;integrated security=true";
using (var conn = new SqlConnection(constr))
{
var cmd = conn.CreateCommand();
cmd.CommandText = "select [master].[dbo].sp_SearchDuplicatedAddress('','','','')";
conn.Open();
var outt = cmd.ExecuteScalar();
Console.WriteLine(outt);
}
}
}
}
I have just installed Postgre SQL on Windows 10. I can connect to the data base via PSQL and pgAdmin fine.
The problem is that I can neither connect to the data base using C# or an .udl-test file.
My C# code:
var connection = new SqlConnection(
"Data Source=localhost;" +
"User id=postgres;" +
"Password=postgres;" +
"connection timeout=10");
connection.Open();
This gives me an exception (server not found).
SqlConnection is for SQL Server only. You could use NpgsqlConnection from Npgsql library. Simple example from library developers:
var connString = "Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase";
using (var conn = new NpgsqlConnection(connString))
{
conn.Open();
// Insert some data
using (var cmd = new NpgsqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO data (some_field) VALUES (#p)";
cmd.Parameters.AddWithValue("p", "Hello world");
cmd.ExecuteNonQuery();
}
// Retrieve all rows
using (var cmd = new NpgsqlCommand("SELECT some_field FROM data", conn))
using (var reader = cmd.ExecuteReader())
while (reader.Read())
Console.WriteLine(reader.GetString(0));
}
http://www.npgsql.org/doc/index.html
I am using SQl CLR for parsing some table column. I want to execute the queries also in C# user defined function. Can somebody give an example to execute select and insert queries in the function?
Thank you in advance.
SqlConnection objSqlConn;
string connString = string.Empty;
connString = "Data Source=(local);Initial Catalog=DB;User ID=uname;pwd=pass;Password=pass";
objSqlConn = new SqlConnection(connString);
objSqlConn.Open();
string query = "Select count(*) FROM [DB].[dbo].[TableName]";
SqlCommand cmdTotalCount = new SqlCommand(query, objSqlConn);
cmdTotalCount.CommandTimeout = 0;
string TotalCountValue = cmdTotalCount.ExecuteScalar().ToString();
return TotalCountValue;
In CLR, you can use existing connection to run queries.
Simple, returning data to client:
var cmd = new SqlCommand("select * from [table]");
SqlContext.Pipe.ExecuteAndSend(cmd);
Returning data via SqlDataReader:
var con = new SqlConnection("context connection=true"); // using existing CLR context connection
var cmd = new SqlCommand("select * from table", con);
con.Open();
var rdr = cmd.ExecuteReader();
SqlContext.Pipe.Send(rdr);
rdr.Close();
con.Close();
Running other commands:
var con = new SqlConnection("context connection=true"); // using existing CLR context connection
var cmd = new SqlCommand("insert into [table] values ('ahoj')", con);
con.Open();
var rsa = cmd.ExecuteNonQuery();
con.Close();
Once you switch to C# you execute queries like you'd normally do from your application (using ADO.NET's SqlConnection and SqlDataReader, using LINQ to SQL or using your custom build data layer).
To connect with the database you have to mention the database username and password in the connection string of your web.config file.
hallo there
This is a very basic question. I am currently a student and have done ASP.NET with C#.
For our purposes it was required to do work with an access database where connecting to it and adding data etc.was very easy.
My feeling is that access is not used much in the real world and would just like to enquire on the easiest and most correct way of establishing a connection to Microsoft Sql Server Database(Transact sql).
In my case the database is called dbActivities with primary data file being dbActivitiesData.mdf.
OleDbDataConnection conn;
conn = new OleDbConnection = #"Provider=Microsoft.Jet.Oledb.4.0:"
#"Data Source=DataBase.mdb";
conn.Open();
Regards
My feeling is that access is not used much in the real world
Unfortunately Access is still very much used in the real world :-)
As far as the correct way is concerned I would recommend you wrapping the connection into a using block to ensure proper handling:
class Program
{
static void Main()
{
var connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\work\DataBase.mdb";
using (var conn = new OleDbConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT Name FROM Customers";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var customerName = reader.GetString(reader.GetOrdinal("Name"));
Console.WriteLine(customerName);
}
}
}
}
}
And as far as Microsoft SQL Server is concerned:
var connectionString = #"Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;";
using (var conn = new SqlConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT Name FROM Customers";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var customerName = reader.GetString(reader.GetOrdinal("Name"));
Console.WriteLine(customerName);
}
}
}
string strSQLCommand;
SqlCommand command;
SqlConnection conn = null;
conn =new SqlConnection("Data Source=serverName\IP;Initial Catalog=dbActivities;UID=User;PWD=Password;Max Pool Size=500;");
strSQLCommand = "Your Command";
command = new SqlCommand(strSQLCommand, conn);
command.ExecuteNonQuery();
conn.Close();
This is a really, really stupid question but I am so accustomed to using linq / other methods for connecting and querying a database that I never stopped to learn how to do it from the ground up.
Question: How do I establish a manual connection to a database and pass it a string param in C#? (yes, I know.. pure ignorance).
Thanks
using (SqlConnection conn = new SqlConnection(databaseConnectionString))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ID", fileID);
conn.Open();
using (SqlDataReader rdr =
cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
if (rdr.Read())
{
// process row from resultset;
}
}
}
}
One uses the SqlCommand class to execute commands (either stored procedures or sql) on SQL Server using ado.net. Tutorials abound.
Here's an example from http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson07.aspx
public void RunStoredProcParams()
{
SqlConnection conn = null;
SqlDataReader rdr = null;
// typically obtained from user
// input, but we take a short cut
string custId = "FURIB";
Console.WriteLine("\nCustomer Order History:\n");
try
{
// create and open a connection object
conn = new
SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();
// 1. create a command object identifying
// the stored procedure
SqlCommand cmd = new SqlCommand(
"CustOrderHist", conn);
// 2. set the command object so it knows
// to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which
// will be passed to the stored procedure
cmd.Parameters.Add(
new SqlParameter("#CustomerID", custId));
// execute the command
rdr = cmd.ExecuteReader();
// iterate through results, printing each to console
while (rdr.Read())
{
Console.WriteLine(
"Product: {0,-35} Total: {1,2}",
rdr["ProductName"],
rdr["Total"]);
}
}
finally
{
if (conn != null)
{
conn.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
}
3 things no one else has shown you yet:
"Stacking" using statements
Setting an explicit parameter type rather than letting .Net try to pick one for you
"var" keyword
.
string sql = "MyProcedureName";
using (var cn = new SqlConnection(databaseConnectionString))
using (var cmd = new SqlCommand(sql, cn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ParameterName", SqlDbType.VarChar, 50)
.Value = "MyParameterValue";
conn.Open();
using (SqlDataReader rdr =
cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
if (rdr.Read())
{
// process row from resultset;
}
}
}