I know I have done this a few times before but for the life of me can't remember how.
I have a database I have created and I want to make a software that only inputs information into the database. The program works but my sql connection is the problem. So to test it out I basically tried to do it direct inserting hard-coded info but it still will not go. where am I going wrong?:
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.Common;
using System.Data.SqlClient;
using System.Data.Sql;
namespace InventoryTracker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static void CreateCommand()
{
SqlConnection myConnection = new SqlConnection("User Id=Jab" + "password=''" + "Data Source=localhost;" + "Trusted_Connection=yes;" + "database=InventoryTracker;" + "Table=Inventory;");
try
{
myConnection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
SqlCommand myCommand = new SqlCommand("INSERT INTO Inventory (ItemName, SerialNumber, Model, Department, Quantity, Notes) " + "Values (string,string,string,string, 1, string)", myConnection);
}
}
}
Thank you in advance! :-)
Your sql connection string is messed up, you need semi-colons between all parameters and your parameters are messed up too. I.e., something like
"Server=localhost;Database=InventoryTracker;Trusted_Connection=True;"
You are mixing trusted mode and specifying the user id -- trusted connection means to use your windows login credentials.
TableName does not go in the connection string.
This site is great for connection string examples http://www.connectionstrings.com/sql-server-2008
You SQL command, "INSERT INTO Inventory (ItemName ..." is pretty messed up too. Should be something like
INSERT INTO Inventory (ItemName ...) values(#ItemName ...)
You then pass in the values like
myCommand.Parameters.Add("ItemName", SqlType.VarChar).Value = "Dozen Eggs";
See Insert data into SQL Server from C# code for a simple example
Just use the SqlConnectionStringBuilder class.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx
Instead of:
"User Id=Jab" + "password=''" + "Data Source=localhost;" + "Trusted_Connection=yes;" + "database=InventoryTracker;" + "Table=Inventory;");
Try:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.UserID = "Jab";
builder.Password = "";
builder.DataSource = "localhost";
builder.InitialCatalog = "InventoryTracker";
// Don't put table name in your connection string
string connection_str = "Data Source = localhost ; uid = db_user; pwd = db_pass; database = db_name; ";
conn = new SqlConnection(connection_str);
conn.Open();
Try changing
"User Id=Jab" + "password=''" + "Data Source=localhost;" + "Trusted_Connection=yes;" + "database=InventoryTracker;" + "Table=Inventory;"
to
"User Id=Jab; " + "Password=''; " + "Data Source=localhost; " + "Trusted_Connection=yes; " + "Initial Catalog=InventoryTracker;"
(Changed upper/lower case, "Database" to "Initial Catalog", removed "Table" and added ";")
Also, you might want to try replacing "Data Source" by "Server".
Don't forget to call myCommand.ExecuteNonQuery to get it to actually execute your query. Without this, you are just creating a command, but not running it.
Related
I understand that this may be considered a duplicate question, but I am at an impasse and i do not know what it is I am doing wrong, I need help. The duplicate question said to use OLEDB in order to write to the Microsoft Access file, where as before I was using the SQL connection to accomplish my task. As far as i can tell there are no syntax, logic, or runtime errors and Visual Studios doesnt have an issue either.
When i run the code and go to add a new entry to the Microsoft Access Database Table, it says it worked, but when I go and look at the file there is NOTHING there. Someone please help me, I have goe through all the links, all the web pages, all the search engines, and I dont know what is wrong. I would love to learn what is wrong and how to fix it so I wont ever have to ask for help again.
Currently I am a college student and I am working on a team assignment. Our task, is to create a window that will take input from a user and then add it as a entry into an Microsoft Access File as if it were a SQL database.
The issue we are having is that we are trying to add the new entry to a local Microsoft Access file under the table named Artist. I have connected to an actual SQL server before and no one else in my group has, even worse no one has done this with using a Microsoft Access file on our PC either.
I have added the Database (Microsoft Access File) in Visual Studios using the Database Configuration Wizard. At first I was using straight SQL do to this and then i was told i need to use OLEDB in order to do this. SO I have implemented in the code and for some reason I still cannot get it to work. If anyone can give me a hand and tell me what it is I am doing wrong, I would greatly appreciate it.
Details that I believe are important for anyone to help me:
The name of the table I am attempting to write a new entry to: Artist
Name of the Microsoft Access File: Kays.accdb
Location of the Microsoft Access file: C:\KayDB\Kays.accdb (local machine)
Once again I would greatly appreciate any help that anyone can give me. I really am curious as to why the code is not working, please help me understand.
My code is as follows:
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.OleDb;
namespace Kay
{
public partial class Kay_Green : Form
{
string Username,Fname, Mname, Lname, streetaddress, city, phonenumber, emailaddress, zipcode, taxIDnummber, state;
string[,] SQLTable = new string[0, 10];
public Kay_Green()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{//Save Button
/*Upon clicking the save button, gather all info and save it into an temp array.
Then send it to the SQL database.*/
/*The order of the data in the array will be the same order in the SQL table.*/
Fname = tbFirstName.Text;
Mname = tbMiddleInitial.Text;
Lname = tbLastName.Text;
streetaddress = tbStreet.Text;
city = tbCity.Text;
state = cbState.Text;
phonenumber = tbPhoneNumber.Text;
emailaddress = tbEmailAddress.Text;
zipcode = tbZipCode.Text;
taxIDnummber = tbTaxID.Text;
Username = tbUserName.Text;
/*SQLTable[0,0] = taxIDnummber;
SQLTable[0,1] = Fname;
SQLTable[0,2] = Mname;
SQLTable[0,3] = Lname;
SQLTable[0,4] = streetaddress;
SQLTable[0,5] = city;
SQLTable[0,6] = state;
SQLTable[0,7] = zipcode;
SQLTable[0,8] = phonenumber;
SQLTable[0,9] = emailaddress;*/
/*Below is the details for the SQL connection*/
string connectstring="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\KayDB\\Kays.accdb";
OleDbConnection connection=new OleDbConnection(connectstring);
OleDbCommand command;
OleDbDataAdapter adapter;
DataTable dt = new DataTable();
string sql ="Insert into ARTIST values ('" + taxIDnummber + "','"
+ emailaddress + "','" + Fname + "','" + Mname + "','"
+ Lname + "','" + phonenumber+"','"+ Username + "','"
+ streetaddress + "','" + city + "','" +state+ "','"
+ zipcode + "')";
try
{
connection.Open();
command = new OleDbCommand(sql, connection);
MessageBox.Show("Connection Open And data added to table! ");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! " + ex.StackTrace.ToString());
}
/*Above is the details for the SQL connection*/
}
private void btnCancel_Click(object sender, EventArgs e)
{//Cancel Button
tbCity.Clear();
tbEmailAddress.Clear();
tbFirstName.Clear();
tbLastName.Clear();
tbMiddleInitial.Clear();
tbPhoneNumber.Clear();
tbStreet.Clear();
tbTaxID.Clear();
tbZipCode.Clear();
tbUserName.Clear();
Close();//Go back to switchboard from here
}
private void btnClear_Click(object sender, EventArgs e)
{//Clear button
tbCity.Clear();
tbEmailAddress.Clear();
tbFirstName.Clear();
tbLastName.Clear();
tbMiddleInitial.Clear();
tbPhoneNumber.Clear();
tbStreet.Clear();
tbTaxID.Clear();
tbZipCode.Clear();
tbUserName.Clear();
}
}
}
This code
command = new OleDbCommand(sql, connection);
sets up a command but does not run it
you need to run this afterwards:
command.ExecuteNonQuery();
This has nothing to do with connection strings
I'm new to coding in C# and have looked around but finding it hard to extrapolate an answer for my problem.
I'm currently just trying to get to grips with adding text and selected text from a combobox into a simple database table. However when I try to add the information I get an error of SqlException was unhandled. I've looked at other answers and saw it maybe something to do with adding a connection, which I've tried but it's still not working...
My code and error message as in the image link below but just in case here is my code also,
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.Data.SqlClient;
using System.Windows.Forms;
namespace SavetoDbTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection test = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\User\\Documents\\Visual Studio 2015\\Projects\\SavetoDbTest\\SavetoDbTest\\Hobbie.mdf;Integrated Security=True"))
{
using (SqlCommand again = new SqlCommand())
{
again.CommandText = "INSERT INTO Table Values('" + textBox1.Text + "', '" + comboBox1.Text + "')";
again.Parameters.AddWithValue("#Name", textBox1.Text);
again.Parameters.AddWithValue("#Hobby", comboBox1.Text);
again.Connection = test;
test.Open();
again.ExecuteNonQuery();
test.Close();
MessageBox.Show("Data Entry Successful");
}
}
}
}
}
+1 for trying to use parameterized queries! But you're not doing it right :-)
again.CommandText = "INSERT INTO Table Values('" + textBox1.Text + "', '" + comboBox1.Text + "')";
again.Parameters.AddWithValue("#Name", textBox1.Text);
again.Parameters.AddWithValue("#Hobby", comboBox1.Text);
This add parameters when the query string doesn't expect them. Probably this is also the cause for the exception you're seeing.
Your query string must look like this:
again.CommandText = "INSERT INTO [Table] Values(#Name, #Hobby)";
Also, TABLE is a reserved word in SQL. So if your table is named Table, you should wrap it in square brackets.
Use this instead of:
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection test = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\User\\Documents\\Visual Studio 2015\\Projects\\SavetoDbTest\\SavetoDbTest\\Hobbie.mdf;Integrated Security=True"))
{
using (SqlCommand again = new SqlCommand())
{
again.CommandText = "INSERT INTO [TableName] Values(#Name,#Hobby)";
again.Parameters.AddWithValue("#Name", textBox1.Text);
again.Parameters.AddWithValue("#Hobby", comboBox1.Text);
again.Connection = test;
test.Open();
again.ExecuteNonQuery();
test.Close();
MessageBox.Show("Data Entry Successful");
}
}
}
As mentioned by PaulF it is always a good practise to use Try..Catch block. It will give you the exception message if the code doesn't works for you. Here you go.
private void button1_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection test = new SqlConnection("YourConnectionStringName"))
{
using (SqlCommand again = new SqlCommand())
{
again.CommandText = "INSERT INTO Table Values(#Name,#Hobby)";
again.Parameters.AddWithValue("#Name", textBox1.Text);
again.Parameters.AddWithValue("#Hobby", comboBox1.Text);
again.Connection = test;
test.Open();
again.ExecuteNonQuery();
test.Close();
MessageBox.Show("Data Entry Successful");
}
}
}
catch (Exception ex)
{
throw ex;
}
}
Check whether it is working or not. Hope atleast it will give you one step ahead result to let you know if any exception arises
Precisely this exception is being thrown because table is a reserved keyword. SQL engine encounters this reserved keyword, when it expects to find a proper name of the table and thus throws an exception. Try specifiying correct table name, because I believe this table name was given just as an example.
Your statement should look a little bit more like this
INSERT INTO MyTable Values ...
Other answers about using parametrized query in incorrect way are also valid.
there are 3 issues in your code.
1) you have reserved keyword for table name, Table
2) SQL query you are building from code is incorrect.
3) You need to specify your command type.
Solution: Change table name to something meaningful, like employeedata or testdata and modify your code according to given below.
again.CommandType = CommandType.Text;
again.CommandText = "INSERT INTO TestData(ColumnName1,ColumnName2) Values('" + textBox1.Text + "', '" + comboBox1.Text + "')";
again.Connection = test;
test.Open();
again.ExecuteNonQuery();
test.Close();
MessageBox.Show("Data Entry Successful");
I am trying to create a sign-up for our movie database. I am trying to establish a connection from the MS Access that we made. But whenever I run my code, I get an error. I am using Visual Studio Express 2012 C#.
Why does my code trigger this error?
"An unhandled exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll Additional information: Syntax error in
INSERT INTO statement."
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;
namespace BigScreen
{
public partial class sign_up : Form
{
private OleDbConnection connection = new OleDbConnection();
public sign_up()
{
InitializeComponent();
}
private void sign_up_Load(object sender, EventArgs e)
{
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\raizel\Desktop\DataBase\Movie_Database.accdb;
Persist Security Info=False;";
}
private void sign_up_FormClosed(object sender, FormClosedEventArgs e)
{
Form1 thisform = new Form1();
thisform.Show();
}
}
private void button1_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "Insert into User ([firstname], [lastname], [username], [password]) values ('" + textBox2.Text + "','" + textBox5.Text + "','" + textBox4.Text + "','" + textBox1.Text + "')";
command.ExecuteNonQuery();
userID++;
MessageBox.Show("Data Saved!");
connection.Close();
}
}
}
User is a reserved word. Bracket it like this to inform the db engine that word is an object name:
Insert into [User] ...
You would be wise to switch to a parameterized query as Bradley hinted but you still need to bracket the reserved word there, too.
User is a reserved word at leat in sql server. You have here in your code some things, you are using concatenation and this is making your code in danger of sql injection, the password can be in clear text in the database you need encryption.
You need to use using in your code to be sure the connection is closed after the insert is complete. If the error throw an exception the connection remain open and you will have problem in future attempts to execute anything. Close your db and make sure you can do an action using the designer and then check your code again.
Try to move to sql server ms access is not a good database for your system.
I made this example using your structure in sql fiddle
I am trying to make my application which have aim to make backup of database on disk and also send it through ftp or mail.
So I made a research and finally I wrote project of Windows service and another project in console which is making a backup of database. Both are working well and both are written in the same Visual Studio but when I am trying to put code of making backups in Windows service it doesn't work. I can't understand why. I tried put code instead of example (which is creating a file and writing one line there and this part is working well) and I even tried to make another method to do it and then call this method.
Windows service is completely the same as here and in the SpadesAdminService class instead of
System.Diagnostics.EventLog.WriteEntry("SpadesAdminSvc",
ServiceName + "::Execute()");
I made this code (is working well - making an empty file on my disk every 5 seconds, should be written "text to file" but files are appearing !):
using (FileStream fs = File.OpenWrite("C:\\place\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".txt"))
{
Byte[] napis = new UTF8Encoding(true).GetBytes("text to files"));
fs.Write(napis, 0, napis.Length);
}
My class of making back up (alone is also working well):
namespace makeBackUpConsole
{
class Program
{
static void Main(string[] args)
{
string dbname = "exampleToniDatabase";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
sqlcon.ConnectionString = #"Server=GRAFIKA-2\SQLEXPRESS;Integrated Security=True;" + "Database=exampleToniDatabase";
string destdir = "C:\\place\\";
if (!System.IO.Directory.Exists(destdir))
{
System.IO.Directory.CreateDirectory("C:\\place\\");
}
try
{
sqlcon.Open();
sqlcmd = new SqlCommand("backup database " + dbname + " to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
MessageBox.Show("Backup database successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error During backup database!");
}
}
}
}
I am copying this class instead of my code to making txt files and Windows Service is not working. Here is a code:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace toni.exampleService.Services
{
public class exampleAdminService : exampleServiceBase
{
public exampleAdminService()
{
this.ServiceName = "exampleAdminSvc";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
}
protected override void OnStop()
{
base.OnStop();
}
protected override int Execute()
{
//using (FileStream fs = File.OpenWrite("C:\\development\\toni\\dd\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".txt"))
//{
// Byte[] napis = new UTF8Encoding(true).GetBytes("DzieĆ i godzina: " + DateTime.Now.ToString("ddMMyyyy_HHmmss"));
// fs.Write(napis, 0, napis.Length);
//}
string dbname = "exampleToniDatabase";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
sqlcon.ConnectionString = #"Server=GRAFIKA-2\SQLEXPRESS;Integrated Security=True;" + "Database=exampleToniDatabase";
string destdir = "C:\\place\\";
if (!System.IO.Directory.Exists(destdir))
{
System.IO.Directory.CreateDirectory("C:\\place\\");
}
try
{
sqlcon.Open();
sqlcmd = new SqlCommand("backup database " + dbname + " to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
MessageBox.Show("Backup database successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error During backup database!");
}
return 0;
}
}
}
Of course all libraries as well linked.
Looking for any advice, please help me.
Thank you in advance and have a nice day.
edit:
Hey, problem solved.
I created a database account (not Windows account) in sql management studio and I putted this account User Id and Password directly into my code in C# in Windows Service.
Anyway maybe somebody will use my code :)
Thanks for reply.
Have you checked that a Windows Service has permissions to write a file in the location you are specifying. Services don't necessarily run as a user, so don't assume that where you can write a file your service can too.
Have you tried writing to a folder underneath c:\ProgramData?
If you don't know precisely what the problem is then you need to find out. Try adding System.Diagnostics.Debugger.Launch(); at service startup and then track the changes inside the debugger.
The Windows Service you have programmed is using "Integrated Security" for your SQL Server.
If you don't want to enter login credentials in your code, you should either set the executing user to your local account or grant the required user (e.g. LocalSystem) access to your database in your SQL Management Studio.
Usually a Windows Service is running as LocalSystem, LocalService or NetworkService. Just change the setting for your Windows Service in services.msc
First off, I'd like to say that this is the most brilliant forum I've encountered in my programming journey, and I've been google-fishing for all the help I can get for the last three months. Great support, and even greater style #necromancer badge.
Enough with the flattery.
I'm doing a practice project, insurance website. Right now, I need to get user input from the textboxes into the database. I have seen plenty of related questions here, but I'm getting an error message on my connection I haven't found on any of the other posts, and I'm so ignorant it's difficult to apply examples that don't fit exactly what I'm doing. (As a side note, my trainer specifically wants the most basic form of this code, and as such told me not to worry about parameterizing the queries for security or to use a try-catch block for exceptions, but many thanks to the answers here for those pointers)
The error message I get is "Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed."
Am I getting my syntax wrong? Am I using the 'TextBox1.Text' value right? Am I just too stupid to be doing this?
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SubmissionPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
String connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\aspnetdb.mdf;Integrated Security=True;User Instance=True";
SqlConnection sqlConn = new SqlConnection(connectionString);
sqlConn.Open();
String thisQuery = "INSERT INTO Customer (" + " Name, SIC_NAIC, Address, City, State, Zip, " + ") VALUES (" + " #TextBox1.Text, #RadioButtonList1.SelecedItem, #TextBox2.Text, #DropDownList1.SelectedItem, #TextBox3.Text" + ")";
SqlCommand thisCommand = new SqlCommand(thisQuery, sqlConn);
thisCommand.ExecuteNonQuery();
sqlConn.Close();
}
}
Check this and use sql parameters:
using (var conn = new SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=aspnetdb;Integrated Security=True;Connect Timeout=30;User Instance=True"))
{
conn.Open();
using (var cmd = new SqlCommand("INSERT INTO Customer (Name,SIC_NAIC) VALUES (#Name,#SIC_NAIC)",conn))
{
try
{
cmd.Parameters.Add("#Name", SQlDbType.VarChar, 50).Value = TextBox1.Text;
cmd.Parameters.Add("#SIC_NAIC", SQlDbType.VarChar, 50).Value = RadioButtonList1.SelecedItem.ToString();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
{
}
throw;
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
Make sure you have downloaded sqlmanagement studio 2008 express.. and then attach asp.netdb on it and change your sql connectionstring.
sql ms
Regards
This error is often caused because the parent instance (for whatever reason) can't copy the system databases to the users local isolated storage folders. Sometimes it is because of a previous install of SQL Express has left files in that directory. Full story here
http://social.msdn.microsoft.com/Forums/en/sqldatabaseengine/thread/f5eb164d-9774-4864-ae05-cac99740949b
could be due to permission issue, check eventlog. you may try removing User Instance=True from connection string
In addition to answers regarding SQL database instances, your SQL query looks wrong. Try changing your embedded query to:
String thisQuery = "INSERT INTO Customer (Name, SIC_NAIC, Address, City, State, Zip) VALUES ('" + TextBox1.Text + "', '" + RadioButtonList1.SelecedItem.Text + "', '" + TextBox2.Text + "', '" + DropDownList1.SelectedItem.Text + "', '" + TextBox3.Text + "', '" + TextBoxZip.Text + "')";
This will format the SQL statement from the values on your form.
NOTE: Assuming field SIC_NAIC and State are storing text values and an additional field for Zip (TextBoxZip).
First of all, if your mdf resides at App_Data, then your connection string is all wrong.
Put the following in your web.config
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\aspnetdb.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
Now call it like
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
Here is a fix for your error. But you should have an instance of SQL Express installed, which I supposecomes standard with Visual Studio.
http://www.aspdotnetfaq.com/Faq/fix-error-Failed-to-generate-a-user-instance-of-SQL-Server-due-to-a-failure-in-starting-the-process-for-the-user-instance.aspx
And while you are at it, please alter your Button_Click event like this
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string sql = "INSERT INTO Customer (Name, SIC_NAIC, Address, City, State, Zip) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}')";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = String.Format(sql,
TextBox1.Text,
RadioButtonList1.SelectedItem.Text,
TextBox2.Text,
DropDownList1.SelectedItem.Text,
TextBox3.Text,
"000000");
using (SqlCommand command = new SqlCommand(query, connection))
{
command.ExecuteNonQuery();
}
}
}
Also keep in mind that you cannot insert RadioButtonList1.SelecedItem or DropDownList1.SelectedItem to database. You must append either .Text or .Value to it as per your requirement.
Ok guys, first of all I'm overwhelmed by the helpfulness I found here. I'll be a stackoverflow-er for life. Thank you all for taking your time and experience to aid a total stranger. I couldn't have gotten this done without it.
I wanted to post the code I ended up with, just so as to have a record of what actually worked for me in case someone with the same issue needs to see the end result. As per #yetanothercoder's recommendation, I placed this connection string in my webconfig file, and it looked like this (from ?xml version... to configuration is just to show where I placed the code, since I had wondered about that myself, the connection string is wrapped between the tags):
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=The-Crushinator\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ArgonautSubmission.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
And, although my trainer assured me that the using block #yetanothercoder suggested should be fine, it wasn't working for me, so I used the example from #chaps' answer, remembering to put in the TextBox4.Text value forgot. The code looks like this:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SubmissionPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
String thisQuery = "INSERT INTO Customer (Name, SIC_NAIC, Address, City, State, Zip) VALUES ('" + TextBox1.Text + "', '" + RadioButtonList1.SelectedItem.Text + "', '" + TextBox2.Text + "', '" + TextBox3.Text + "', '" + DropDownList1.SelectedItem.Text + "', '" + TextBox4.Text + "')";
using (SqlConnection sqlConn = new SqlConnection(connectionString))
{
sqlConn.Open();
using (SqlCommand command = new SqlCommand(thisQuery, sqlConn))
{
command.ExecuteNonQuery();
}
}
}
}
Next came the more convoluted part. To rid myself of the dreaded "Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed" error message, I followed this link from #yetanother coder,
and found that I needed to install Sql Server Management Studio Express. I had to use Microsoft Web Platform Installer because when I tried to follow the instructions at msdn.com for downloading ssmse, I kept getting a cyclical error. I installed ssmse, opened up the query window with the 'new query' button, and executed this command
exec sp_configure 'user instances enabled', 1.
Go
Reconfigure
then I restarted sql server, added a new database to my asp.net project, and BAM! It worked! User info was saved into the database, where it was supposed to go! I had been so conditioned to expecting failure from my code that it felt like watching my first rocket make it into orbit. Awesome. Thanks again, everyone, and I hope this helps someone in a similar situation.