Issue with connecting to SQL Server database from Visual Studio - c#

I've created a simple Windows Forms application in C# and now find it hard to connect it to a SQL Server database. I've created the database within Visual Studio itself. However, once I try to insert data I get a SQL exception. My guess is there is problem in the connection data source i.e the con variable. Please help me find a solution.
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;Initial Catalog=Database1;Integrated Security=SSPI");
SqlCommand cmd;
SqlDataAdapter adapt;
if (textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "")
{
cmd = new SqlCommand("insert into [dbo].[user] (Id, username, password) values (#id, #name, #state)", con);
con.Open();
cmd.Parameters.AddWithValue("#id", textBox1.Text);
cmd.Parameters.AddWithValue("#name", textBox2.Text);
cmd.Parameters.AddWithValue("#state", textBox3.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Successfully");
}
else
{
MessageBox.Show("Please Provide Details!");
}
The database file name is
\WindowsFormsApplication1\WindowsFormsApplication1\Database1.mdf

If you created the database on an actual instance of SQL Server (this can be a local instance on your machine), it appears as though your connection string's data source isn't quite right.
Data Source=DESKTOP-XXXXXXX/Shenal Burkey
There are two problems with this, first the slash (/) should actually be a backslash (). Second, after the slash you have 'Shenal Burkey' with a space. SQL Server instance names cannot contain space characters. That being said, if you installed SQL Server as a named instance, you need to specify the named instance in that place, if you accepted the default instance name it should be 'MSSQLSERVER'. If you are using the default instance name, you can either specify your connection string like this:
Data Source=DESKTOP-XXXXXXX\MSSQLSERVER
or you can omit the instance name entirely and just use:
Data Source=DESKTOP-XXXXXXX
Also, just a tip, you will notice I replaced the specifics of your DESKTOP's hostname with X's, personally I'd recommend editing your question and doing the same. It may not seem like it would be useful, but someone might just pick that up and find a crafty way to do some damage. Better safe than sorry.

Related

Trying to make a select from db table via 2 entries - login

private bool CheckIfExist(string username, string password)
{
SqlConnection conn = new SqlConnection("Data Source=
(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Radi\\Desktop\\
WebSiteF86454\\WebSiteF87300\\App_Data\\Database.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.TableUsers WHERE Username=#username and
UserPassword=#password", conn);
cmd.Parameters.AddWithValue("#Username", username);
cmd.Parameters.AddWithValue("#password", password);
conn.Open();
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adpt.Fill(ds);
conn.Close();
int count = ds.Tables[0].Rows.Count;
if (count == 1) { return true; }
else { return false; };
}
Hello, I'm pretty new to sql so apologies if my question has a trivial answer.
I'm trying to make a login check via table in my database. With the code above you can see i'm checking for entries in a table based on 2 fields - username and password. I am getting an error at the SqlCommand - tells me no such table exists. For the connection string i opened server explorer -> right click on my database and copied the whole thing where it says "connection string", so i'm positive it's correct.
I have 2 tables (or at least i think so) in my database - one that stores some other content and one that stores user information. I can see the other one - called Comments, but I cannot see the table for user content (the one i need to refer to). I'll attach some screenshots to show what exactly I see.
What am I doing wrong? Am i creating the table in a wrong way? Am i refering to it in an invalid way? Any help will be appreciated, thanks. Table that i am NOT seeing or able to select is TableUsers. As you can see, i see it on the visual studio, but not in the SQL managment studio.
Agan - error is that i cannot refer to the table i need.
If it says "No such table..." then you misspelled table name. Check again. I would check list of tables with show tables from [database]; from code and list it in some datatable.
Still, "No such table..." says that your ConnectionString is valid.
BTW, I would suggest to you, if you only need true/false from your query, then, you rather use select count(*) from [table] where password=#password and user=#user. Then, instead filling dataset/datatable, and then counting rows, rather use ExecuteScalar to store it to integer variable - it's faster and less resource hungry.

Insert integer value into SQL Server database from C#

I am trying to insert an integer value into a SQL Server database as below when I run the program there are no any errors, but the table doesn't get updated with values. I have searched on the internet and I am doing the same can anyone help to find what I am doing wrong.
Note: I already defined "connectionString" as a string on the form class
private void btnUpdate_Click(object sender, EventArgs e)
{
int totalincome=600;
int totaldeductions = 10;
connectionString = ConfigurationManager.ConnectionStrings["BudgetApp.Properties.Settings.MainDataBaseConnectionString"].ConnectionString;
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand("INSERT INTO Totals(TotalIncome, TotalDeductions) VALUES (#TotalIncome, #TotalDeductions)", con);
cmd.Parameters.AddWithValue("#TotalIncome", totalincome);
cmd.Parameters.AddWithValue("#TotalDeductions", totaldeductions);
cmd.ExecuteNonQuery();
MessageBox.Show("Done !!");
}
The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MainDataBase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MainDataBase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
Code Seems correct,Perhaps you are checking the wrong DB?. I would add a Try/catch for exceptions. And remember to close connection after executing query. Regards
check your database column datatype,use try catch.
and try to replace cmd.Parameters.AddWithValue("#TotalIncome", totalincome); to cmd.Parameters.Add("#Number", SqlDbType.Int).Value = totalincome;
try
{
int totalincome=600;
int totaldeductions = 10;
connectionString = ConfigurationManager.ConnectionStrings["BudgetApp.Properties.Settings.MainDataBaseConnectionString"].ConnectionString;
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand(#"INSERT INTO Totals(TotalIncome, TotalDeductions) VALUES (#TotalIncome, #TotalDeductions)", con);
cmd.Parameters.Add("#Number", SqlDbType.Int).Value = totalincome;
cmd.Parameters.Add("#Number", SqlDbType.Int).Value = totaldeductions;
//cmd.Parameters.AddWithValue("#TotalIncome", totalincome);
//cmd.Parameters.AddWithValue("#TotalDeductions", totaldeductions);
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}

C# mdf local database

I googled for half a day how to set the path of my database so if I put it on an other computer it will work. I would keep googling but I really need the answer really fast... I'll have to use it to a competition in few hours.
string path = Path.Combine(Application.StartupPath, "Database1.mdf");
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + path + ";");
conn.Open();
SqlCommand command = new SqlCommand("SELECT NAME FROM DATA", conn);
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
string text = reader.GetString(0);
MessageBox.Show(text);
}
SqlCommand c = new SqlCommand("INSERT INTO DATA (id, name) VALUES(i, v)", conn);
c.Parameters.AddWithValue("#i", 1);
c.Parameters.AddWithValue("#v", "Jack");
c.ExecuteNonQuery();
conn.Dispose();
This code is working for selection but not for insertion. Then I hardcoded the path into:
String s = #"C:\Users\Radu\Documents\Visual Studio 2013\Projects\WindowsFormsApplication7\WindowsFormsApplication7\Database1.mdf";
and it works for both so it's not the SQL statement that is wrong.
So my question is: what is the path I should put into my SqlConnection object so that when they get my source code on my competition and test it on another pc it will work.
LocalDB is meant exclusively for development. You cannot use it in production. In your case, 'production' means the competition. Unless the competition organizer specifies that they support a SQL Server instance for you to connect to, and give out the connection parameters (ie. very unlikely), you shouldn't use use SQL Server in your project.
You can put the MDF file on any file share that your computer has access to. Just alter the path variable to point at the correct file share.
See answers to your question here Can SQL Server Express LocalDB be connected to remotely?

how to update table data in sql database

I am using asp.net for my project , and I am using the following code , but its not working correctly
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=E:\\WEB_PROJECT\\App_Data\\ASPNETDB.MDF;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "UPDATE info SET fname = #fn, lname = #fl, phone= #ph, recoveryq=#rq, recoverya=#ra WHERE username = #un";
cmd.Parameters.AddWithValue("fn", TextBox3.Text);
cmd.Parameters.AddWithValue("fl", TextBox4.Text);
cmd.Parameters.AddWithValue("ph", TextBox5.Text);
cmd.Parameters.AddWithValue("rq",TextBox6.Text);
cmd.Parameters.AddWithValue("ra",TextBox2.Text);
cmd.Parameters.AddWithValue("un",line);
cmd.ExecuteNonQuery();
con.Close();
Advice plzz i m confused !!! :(
As I've said before on this site - the whole User Instance and AttachDbFileName= approach is flawed - at best! Visual Studio will be copying around the .mdf file and most likely, your UPDATE works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the con.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. ASPNETDB)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=ASPNETDB;Integrated Security=True
and everything else is exactly the same as before...
cmd.Parameters.AddWithValue("#fn", TextBox3.Text);
You have to specify the parameter name along with '#' .

How to insert data into a Microsoft Access Database?

I'm trying to insert data into a Microsoft Access Database.
I inserted data into the Access database, but the first and second time are the only times that show the data I inserted. When I rebuild my application, the data I inserted is gone. I don't know where they go and not show. I use C# with the .NET framework to develop. Here's the relevant part of the code:
OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["Constr"].ConnectionString);
OleDbCommand com = new OleDbCommand();
com.Connection = con;
com.CommandText = "Insert into Language(English,Type,Thai) values(#eng,#type,#thai)";
com.Parameters.AddWithValue("#eng", english);
com.Parameters.AddWithValue("#type", type);
com.Parameters.AddWithValue("#thai", thai);
con.Open();
com.ExecuteNonQuery();
I wrote that code, but I think it is strange. It doesn't show any errors or exceptions, but my data is not inserted correctly. Is this the correct way to insert data? If so, why it it not getting inserted?
When I rebuild my application, the data I inserted is gone
I suspect your database is being overwritten when the application is rebuilt.
This can happen, for example, if your application contains an MDB file that is copied to the output directory on build, and is used from the output directory.
I think Language should be a reserve word and you should wrap it in [] brackets.
Also consider wrapping the code in using blocks, like
using (OleDbConnection con = new OleDbConnection(...))
{
using (OleDbCommand com = new OleDbCommand(sqlString, con))
{
//code
}
}
Other than this [possible issue with table name and that you are not closing your connection], I don't see anything wrong with the code.
You define parameters for the query, but I don't see anywhere those parameters are bound to actual data...
Try some simple tests that replace the variables you're passing in as parameters with actual values, so you can isolate the problem:
In other words, replace this:
com.Parameters.AddWithValue("#eng", english);
com.Parameters.AddWithValue("#type", type);
com.Parameters.AddWithValue("#thai", thai);
With something like this:
//I don't know the data types of your fields, so I'm guessing
com.Parameters.AddWithValue("#eng", "Test1");
com.Parameters.AddWithValue("#type", myEnum.Latin);
com.Parameters.AddWithValue("#thai", "Test1a");
If that works, then your problem probably lies with the english, type, and thai variables and you'll want to make sure they're getting the data you think they should be getting.
May be ur connection string not correct you can it by using .udl file
just follow the link
http://www.gotknowhow.com/articles/test-a-database-connection-string-using-notepad
You can also check the code shown below
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\ruby\\Desktop\\screenShots\\ruby.mdb;Persist Security Info=False");
con.Open();
OleDbCommand cmd = new OleDbCommand("insert into raj(Name,Roll) values('XYZ',12);",con);
cmd.ExecuteNonQuery();

Categories