WPF App run SQL Server Scripts - c#

I often have to 'Generate Scripts' for stored procedures on SQL Server Management Studio. I need to create a WPF app that will take the file produced and execute it. I know you can do this:
SqlCommand insert = new SqlCommand(sql, conn);
insert.ExecuteNonQuery();
If I pass the entire scripts file text into sql, will this execute everything?

Look at this: How to execute an .SQL script file using c#
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.IO;
using System.Data.SqlClient;
[...]
private void Execute(object sender, EventArgs e)
{
string sqlConnectionString = #"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ccwebgrity;Data Source=SURAJIT\SQLEXPRESS";
FileInfo file = new FileInfo(#"E:\Project Docs\MX462-PD\MX756_ModMappings1.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
file.OpenText().Close();
}

Related

Retrieve data from SQL Server database using ajax method C#

I'm new to C# and javacript. I'm doing my first program on Visual Studio and I have one problem to retrieve data from a SQL Server database.
I want to retrieve data from SQL Server and convert it to Json by using an ajax method. But when I start my web page I can see only the table empty, so I think I have not a good method to connect to my data base.
Here is the code for my WebMethod used to retrieve data and convert to Json:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
using Newtonsoft.Json;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string LoadData()
{
string strcon = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("select * from kit", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return JsonConvert.SerializeObject(ds.Tables[0]);
}
Please I need your Help I have done several days on this program. Thanks for all your help.
Your CommandType should be Text and not StoredProcedure since you are using a string SQL command and not a Stored Procedure.

How do I use C# queries on a prexisting database(SQLite database)?

I have run into a problem where my C# code is creating a whole new database instead of using a preexisting one. Then my program runs into errors where the program cannot find the table to insert the information even though the preexisting database has the table because the code itself is looking at the new table. Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Finisar.SQLite;
namespace WestSlope
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SQLiteConnection sqlite_conn;
SQLiteCommand sqlite_cmd;
//SQLiteDataAdapter sqlite_datareader;
sqlite_conn = new SQLiteConnection("DataSource=ClientLogDB.db;Version=3;New=True;Compress=True;");
//open conection
sqlite_conn.Open();
//create sql commands
sqlite_cmd = sqlite_conn.CreateCommand();
//Let SQLite command know query is known
sqlite_cmd.CommandText = "INSERT INTO ASAM (ASAMone, ASAMtwo, ASAMthree, ASAMfour, ASAMLim, ASAMLimEX) VALUES ('Had to call', 'Reffered', 'Had to call', 'Watched', 1 , 'Injured legs');"
;
//execute query
sqlite_cmd.ExecuteNonQuery();
sqlite_conn.Close();
}
}
}
What the code is supposed to do is when the user presses a button the program will save information to the preexisting database; but, as you can see the program is making a new database instead of using the preexisting one.
Use new=false in your connection string to use existing database file.
Following should be the connection string:
sqlite_conn = new SQLiteConnection("DataSource=ClientLogDB.db;Version=3;New=False;Compress=True;");

Importing Excel sheet into SQL Server with C#

I am working on writing a simple program to import an excel sheet into my database but I am running into an error of:
Could not find installable ISAM
I am not sure what this means and after hours of searching with so many different topics I have turned to SO. There is a lot of talk of Jet and ACE where I am not sure what the difference is but here is the rundown: I have an excel file called test or test1 and I just want to import the first sheet in the file. here is my source code so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
string filePath = null;
public Form1()
{
InitializeComponent();
}
//Method to check database connection
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
connetionString = "Data Source=Zach-PC;Initial Catalog=master;Integrated Security=SSPI;";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
//Method to select a file
private void button2_Click(object sender, EventArgs e)
{
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Zach/Documents/test1.xls;Extended Properties=Excel 12.0,HDR=Yes;IMEX=1";
// Create Connection to Excel Workbook
using (OleDbConnection connection =
new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand
("Select * FROM [Sheet1$]", connection);
connection.Open(); //HERE IS WHERE THE ERROR IS
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=Zach-PC;Initial Catalog=master;Integrated Security=True";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "Table";
bulkCopy.WriteToServer(dr);
MessageBox.Show("Data Exoprted To Sql Server Succefully");
}
}
}
}
}
}
Am I approaching this in the right manor?
You need to wrap Extended Properties part of the connection string in the quotation marks:
// here and here
// --> v v
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Zach/Documents/test1.xls;Extended Properties=""Excel 12.0,HDR=Yes;IMEX=1""";
The Office oledb driver is probably not installed on your computer. You should download it from microsoft website. After the installation, your code should run.
If you are reading office 2007 (or newer) excel files then I will suggest to use Open source library Epplus to read the excel file.It is purely .NET library and you wont be dependent on oledb driver.
epplus
EPPlus is a .net library that reads and writes Excel 2007/2010 files using the Open Office Xml format (xlsx).
you can easily read an excel file into datatable using this library. have a look at this thread
How convert stream excel file to datatable C#?

C# 2010 Express + SQL Server 2008 Express - Connection "Login failed"

I am actually developing a Windows Forms Application with Visual C# Express 2010 which would use (read/write) data from a SQL Server 2008 Express DB
I have created my DB with SQL Server Management Studio (2008 Express),
I understand the instance is named ATLELAG786576\SQLEXPRESS
My DB is called 'TEST'
Looking at my DB 'TEST' Properties in SQL Server Management Studio (2008 Express):
Under Files, I am (ATLE\bneveux) the owner of the DB
Looking under Security, Logins, Mylogin (ATLE\bneveux)
My default DB is 'TEST'
Server roles are 'public' + 'sysadmin'
User Mapping DB 'TEST' User 'dbo' Default Schema 'dbo'
In my C# application
app.config:
<?xml version="1.0" encoding="utf-8" ?> <configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="connectionStringTestDb"
connectionString="Data Source=ATLELAG786576\SQLEXPRESS;Initial Catalog=D:\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\TEST.mdf;Integrated Security=True;Connect Timeout=30;User Instance=False"
providerName="System.Data.SqlClient" />
</connectionStrings> </configuration>
dbConnection.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace SQLServerConnectionDemo
{
class dbConnection
{
public static SqlConnection newCon;
public static string connectionStringTestDb = ConfigurationManager.ConnectionStrings["connectionStringTestDb"].ConnectionString;
public static SqlConnection GetConnection()
{
newCon = new SqlConnection(connectionStringTestDb);
return newCon;
}
}
}
dbAccess.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace SQLServerConnectionDemo
{
class dbAccess
{
SqlConnection conn;
public dbAccess()
{
conn = dbConnection.GetConnection();
}
//Method insert new in tblEmployees
public void addEmployee(string Id, string Name, string Email)
{
if (conn.State.ToString() == "Closed")
{
conn.Open();
}
SqlCommand newCmd = conn.CreateCommand();
newCmd.Connection = conn;
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = "INSERT INTO tblEmployees VALUES ('"+ Id +"','"+ Name +"','"+ Email +"')";
newCmd.ExecuteNonQuery();
}
}
}
in a form formEmployeeAdd.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SQLServerConnectionDemo
{
public partial class formEmployeeAdd : Form
{
dbAccess access = new dbAccess();
public formEmployeeAdd()
{
InitializeComponent();
}
private void btnInsert_Click(object sender, EventArgs e)
{
access.addEmployee(txtId.Text, txtName.Text, txtEmail.Text);
MessageBox.Show("Data successfully added");
}
}
}
And here the error message I always get when trying to run this process:
System.Data.SqlClient.SqlException (0x80131904): Cannot open database "D:\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\TEST.mdf" requested by the login. The login failed.
Login failed for user 'ATLE\bneveux'.
Note that I have never really been able to add my Data Source in Visual C# 2010 Express so I could manage the DB from VS, I always get the following error message:
Unable to open the physical file "D:\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\TEST.mdf". Operating system error 32: "32(Le processus ne peut pas accéder au fichier car ce fichier est utilisé par un autre processus.)".
An attempt to attach an auto-named database for file D:\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\TEST.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
Try replacing
Initial Catalog=D:\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\TEST.mdf
with simply
Initial Catalog=TEST

Where/how do I write T-SQL in my C# code and get the result (Visual Studio 2008)

I am trying to write t-sql in C# (visual studio). I have this code to connect to the database:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
connetionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Xtreme\\Desktop\\CardsDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
Where/how do I write the T-SQL code and how do I get the result?
Can someone give me an simple select example in my code?
You can use DataAdapter.Fill Method:
try
{
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM Employee", cnn))
{
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// Render data onto the screen
dataGridView1.DataSource = t; //if you want.
}
}
catch (Exception ex)
{
MessageBox.Show("Problem!");
}
Create a SqlCommand and set the CommandType to CommandType.Text. Then add your SQL to the CommandText property of the SqlCommand.
SqlCommand command = new SqlCommand(commandName, (SqlConnection)Connection);
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM MyTable";
IDataReader result = command.ExecuteReader();
Ardman already showed you how to execute any arbitary sql command. But what i didn't answer very well, is where to put your sql statement.
I think it is a very bad behaviour and also not very good to read if you put your statement directly into the code.
A better method (in my eyes) is the following:
Within your project create a new folder (maybe called Queries)
Right click this folder and select Add - New Item
In the dialog just select Textfile and give it the name about what this query will do
Make sure you replace the file extension from .txt to .sql
Just put your statement right into this file
In the Resource Editor add this file as a resource
Now you can access this sql statement within your project just by using Properties.Resources.MySqlStatement

Categories

Resources