C# How to connect the local database (access) - c#

I have a question about C#. I wrote a function using ASP.net, when the user clicks the button, it should call this function and insert the sql to the local database. However, I don't know why it is not working. Can anyone help me?
My local database is Access, which is stored under the 'App_Data' folder.
protected void button1_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection(connectionString);
// I think the problem is here, but I don't know how to do
SqlCommand myCommand = new SqlCommand("INSERT INTO [car] ([carName], [carType]) VALUES (#carName, #carType)", myConnection);
SqlParameter carName= myCommand.Parameters.Add("#carName", SqlDbType.Text);
SqlParameter carType= myCommand.Parameters.Add("#carType", SqlDbType.Text);
carName.Value = carNametb.Text;
carType.Value = carTypetb.Text;
myConnection.Open();
myCommand.ExecuteNonQuery();
// need to close() the connection where?
}

You need to declare your connection string.
string connectionstring = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;";

http://www.connectionstrings.com/ has lots of good information about different connection strings you might need.
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccess2007file.accdb;Persist Security Info=False;

You have to pass connections string
Go to Server explorer
Right click on database and select properties
There u will find Connection String
Copy the connection string and store connectionstring

Related

How to resolve "Ensure SQL Server Browser is running" , when it is

I'm creating an Android App using Xamarin Forms in Visual Studio 2017. Since this includes storing data, I'm using SQL Server 2017 to accomplish this. When I run my code, and debug the line "conn.Open()", I get an error stating that I should ensure that SQL Server Browser is running. However, when I check SQL Configuration Manager, it is running.
Some things I've tried
- Making sure that the connection string in SQL Server matches the connection string in my code
- I've tried changing what the SQL Server Browser is logged into (Whether it's local system, local service, etc.)
- I've tried several different methods of implementing an insert statement in my code
public class ConnectionManager
{
public static SqlConnection NewCon;
public static string ConStr = #"Data Source=DESKTOP-V83O00S\SQLEXPRESS;Initial Catalog=ResourceSharing;Integrated Security=True";
public static SqlConnection GetConnection()
{
NewCon = new SqlConnection(ConStr);
return NewCon;
}
}
private void Button_Clicked(object sender, EventArgs e)
{
SqlConnection conn;
conn = ConnectionManager.GetConnection();
conn.Open();
string cmdString = "INSERT into Login values(#username,#password)";
SqlCommand sqlCommand = new SqlCommand(cmdString, conn);
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Parameters.Add("#username", SqlDbType.Text).Value = "josh123";
sqlCommand.Parameters.Add("#password", SqlDbType.Text).Value = "pwd321";
sqlCommand.ExecuteNonQuery();
conn.Close();
}
Expected Result: 1 record in my Login table
Actual Result: Error asking me to ensure SQL Server Browser is running.
Any feedback or suggestions on either how to fix this problem or what alternative route I can take that would work?

Can't connect to SQL Server with C# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
connetionString = "My_Connection";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO person " +
"(name, lastname, phone) VALUES('#name', '#lastname', '#phone')");
cmd.CommandType = CommandType.Text;
cmd.Connection = cnn;
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#lastname", txtLastname.Text);
cmd.Parameters.AddWithValue("#phone", Convert.ToInt32(txtPhone.Text));
MessageBox.Show("Successful");
cnn.Close();
}
catch (SqlException ex)
{
MessageBox.Show("You failed!" + ex.Message);
}
}
There is a number of issues with this code. It appears that you're trying to reference a connection string from a configuration file. However, you can't just pass the name to the connection - you must actually retrieve it and assign it to your SqlConnection. Alternatively, you can hardcode a connection string, plenty of examples of those are available at connectionstrings.com.
It is usually not a good idea to put the connection string directly in your application however, as you need to reuse them throughout your application and it's best to have them declared in a central location.
private void button1_Click(object sender, EventArgs e)
{
// retrieve connection from configuration file
// requires a reference to System.Configuration assembly in your project
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["My_Connection"].ConnectionString;
//alternatively, hardcode connection string (bad idea!)
//string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand("INSERT INTO person (name, lastname, phone) VALUES(#name, #lastname, #phone)", connection))
{
// you should avoid AddWithValue here, see http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
// thanks marc_s! http://stackoverflow.com/users/13302/marc-s
command.Parameters.AddWithValue("#name", txtName.Text);
command.Parameters.AddWithValue("#lastname", txtLastname.Text);
command.Parameters.AddWithValue("#phone", Convert.ToInt32(txtPhone.Text));
connection.Open();
command.ExecuteNonQuery();
}
MessageBox.Show("Successful");
}
The connection string is passed to the connection in its constructor, and the connection is passed to the command via its constructor.
Notice that there is no need to explicitly close the connection, the using statements take care of those for you. When the variable is out of scope, the connection will be closed, even if there is an exception.
An example of a connection string in your configuration file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="My_Connection" providerName="System.Data.SqlClient" connectionString="Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;" />
</connectionStrings>
</configuration>
You have to write valid connetionString. If you ask what connection string is?
Here is answer
'In computing, a connection string is a string that specifies information about a data source and the means of connecting to it. It is passed in code to an underlying driver or provider in order to initiate the connection. Whilst commonly used for a database connection, the data source could also be a spreadsheet or text file.
The connection string may include attributes such as the name of the driver, server and database, as well as security information such as user name and password.'
Something like that
Server=myServerAddress;Database=myDataBase;User Id=myUsername; Password=myPassword;
They are a number of things to worry about when connecting to SQL Server on another machine.
Host/IP Address of the machine
Initial Catalog (database name)
Valid username/password
Very often SQL server may be running as a default intance which means you can simply specify the hostname/ip address but you may encounter a scenario where it is running as a named instance (Sql Express for instance). In this scenario you'll have to specify hostname\instance name
Your connection string is missing! Define it or get from your config. "My_Connection" doesn't contain server, database, user, password. Use something like:
var connectionString = "Data Source=ServerName; Initial Catalog=DataBaseName; User id=UserName; Password=Secret;";
using (SqlConnection connection = new SqlConnection("Data Source=ServerName; Initial Catalog=DatabaseName;User ID=UserName;Password=Password"))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection; // <== lacking
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO person " +
"(name,lastname,phone) VALUES('#name', '#lastname', '#phone')";
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#lastname", txtLastname.Text);
cmd.Parameters.AddWithValue("#phone", Convert.ToInt32(txtPhone.Text));
try
{
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
}
catch(SqlException)
{
// error here
}
finally
{
connection.Close();
}
}
}
Here is the working code.
Sincerely,
Thiyagu Rajendran
**Please mark the replies as answers if they help and unmark if they don't.

Getting Error while connecting to DB using c#

Is there anything wrong with this code? Please help me out.
protected void Button_Click(object sender, EventArgs e)
{
string cs = "Data Source=SFSIND0402;Initial Catalog=TestDB;Integrated Security=SSPI;Provider=Microsoft.ACE.OLEDB.12.0";
OleDbConnection conn = new OleDbConnection(cs);
conn.Open();
OleDbCommand insert = conn.CreateCommand();
insert.CommandText="insert into Employee(ID, Name, Sex, Salary) values('003','Vedpathi','M',25000)";
insert.Connection = conn;
insert.ExecuteNonQuery();
conn.Close();
}
I am getting the following error:
Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done
(on line 22:conn.Open();)
When connecting to an MS SQL database, use the MS SQL providers:
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var cmd = new SqlCommand(commandText, connection);
cmd.ExecuteNonQuery();
}
In addition to the solution Luaan mentioned, you should store your connection string in the config file of the app and also encrypt it.
Even if you use SSL encryption when communicating with the DB, an ill-indended person can extract the string variables, if he / she runs the application on his / her machine.

How to insert data from ASP.Net to MS SQL Server?

This question has been asked for several times here. I read posted questions but I still have problem. I'm trying to insert values from ASP.Net form to SQL Server. I created a sample website to work on inserting data into Sql table. SQL Database's name is "TestDatabaseDB" which has one table called "Person". Person table has 4 columns. They are ID, FirstName, LastName, NationalID. The type of ID is "int". I set "Is Identity:Yes". So SQL will assign an ID to each inserted record. It just doesn't work. When I click the button nothing happens. It must insert data into database table or clears the textboxes at least but it doesn't.
I tried
SqlConnection conn= new SqlConnection(#"Data source=.\SQLEXPRESS; AttachDBFilename=""|DataDirectory|\TestWebSiteDB.mdf""; integrated user=true; User Instance=true")
It didn't work. So I changed that into:
SqlConnection conn = new SqlConnection("Data Source=. ; Database=TestWebSiteDB; Integrated Security=true");
Didn't make any difference. Here is my code:
using System;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnRegister_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=. ; Database=TestWebSiteDB; Integrated Security=true");
SqlCommand insert = new SqlCommand("insert into Person(FirstName, LastName, NationalID) values(#Name, #Surname, #ID)" ,conn);
insert.Parameters.AddWithValue("#Name", txtboxName.Text);
insert.Parameters.AddWithValue("#Surname", txtboxFamilyName.Text);
insert.Parameters.AddWithValue("#ID", txtboxNationalCode.Text);
try
{
conn.Open();
insert.ExecuteNonQuery();
}
catch
{
LMsg.Text="Error when saving on database";
conn.Close();
}
txtboxName.Text="";
txtboxFamilyName.Text = "";
txtboxNationalCode.Text = "";
}
}
Any help would be appreciated.
Try this:
protected void Register_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\DB_Users.mdf;Integrated Security=True");
SqlCommand insert = new SqlCommand("insert into tbl_users(name, username, password,email) values(#name, #username, #password,#email)", conn);
insert.Parameters.AddWithValue("#name", txtname.Text);
insert.Parameters.AddWithValue("#username", txtusername.Text);
insert.Parameters.AddWithValue("#password", txtpassword.Text);
insert.Parameters.AddWithValue("#email", txtemail.Text);
try
{
conn.Open();
insert.ExecuteNonQuery();
lbl_msg.Text = "Register done !";
//lbl_msg.Text = "ثبت نام با موفقیت انجام شد";
}
catch (Exception ex)
{
lbl_msg.Text = "Error: "+ex.Message;
//lbl_msg.Text = "خطا در ارتباط با پایگاه داده";
conn.Close();
}
}
It works for me.
You need to track what error you are getting as follows. Because it is not possible to help you without the actual error.
catch(Exception ex)
{
LMsg.Text=ex.Message;
}
Also you need to use finally in your code for closing connection rather than closing it into the catch block.
finaly
{
conn.Close();
}
check your connection string. in conn.open() you get exception ?
To create a data connection to a SQL Server database
In Server Explorer/Database Explorer click Connect to Database.
In the Choose Data Source dialog box, select Microsoft SQL Server, and then click OK.
If the Add Connection dialog box opens, and the Data source is not Microsoft SQL Server, click Change to open the Choose/Change Data Source dialog box
. For more information, see Choose/Change Data Source Dialog Box.
Select a server name from the drop-down list, or type the name of the server where the database you want to access is located.
Based on the requirements of your database or application, select either Windows Authentication or use a specific user name and password to log on to the SQL Server (SQL Server Authentication).
For more information, see Add/Modify Connection (Microsoft SQL Server).
Select the database you want to connect to from the drop-down list.
Click OK.
then copy generated connection string to your program.
when you install sql server the server name and the setting you choose for installing .affect your connection string.
for more inforamtion on installing sql server see the
installing sql server express edition
and also check this for connecting asp.net application to sql server
Asp.net connection to SQL Server
Actually the list view has a default method call onsorting. It will automatically sort the list view. onsorting will call the function as below.The function no need put any statement.
protected void Sorting(object sender,ListViewSortEventArgs e)
{
}
For the link button in list view u just simply put the tag like that:
<asp:ListView ID="DisplayContent" runat="server" onSorting="Sorting">
<asp:LinkButton ID="Name" runat="server" CommandName="Sorting" CommandArgument="Name" Text="Name" />
Try following steps:
Step1: Instead of putting you query in your C# file, declare a stored procedure for it like bellow:
CREATE PROCEDURE [dbo].[ADD_PERSON_SP]
/*Type of this variables should be their column types*/
#firstName varchar(MAX),
#lastName varchar(MAX),
#nationalID varchar(MAX)
AS
BEGIN
INSERT INTO [dbo].[Person] (FirstName, LastName, NationalID)
VALUES (#firstName,#lastName,#nationalID)
END
Step2: Using Stored Procedure where you need:
SqlConnection con = new SqlConnection(connectionString);
SqlCommand com = new SqlCommand("ADD_PERSON_SP", con);
com.Parameters.AddWithValue("#firstName", txtboxName.Text);
com.Parameters.AddWithValue("#lastName", txtboxFamilyName.Text);
com.Parameters.AddWithValue("#nationalID", txtboxNationalCode.Text);
com.CommandType = CommandType.StoredProcedure;
try
{
con.Open();
com.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
Keep in mind to:
Do not put db related stuffs in your C# files
Try to choose better names for your variables(specially for controls)
This may help you with connectionString
I hope that help
protected void btnRegister_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=. ; Database=TestWebSiteDB; Integrated Security=true");
SqlDataAdapter dap = new SqlDataAdapter("insert into Person(FirstName, LastName, NationalID) values(#Name, #Surname, #ID)", con);
dap.InsertCommand(txtboxName.Text, txtboxFamilyName.Text,txtboxNationalCode.Text);
txtboxName.Text="";
txtboxFamilyName.Text = "";
txtboxNationalCode.Text = "";
}

connect to MySQL webserver with C#

I try to connect to a MySQL database on a server a friend of mine has created, but it still says it cannot connect to the server!
Here is my code:
String connectionString = "Persist Security Info=False;database=qwertyui;server=www.qwertyuiop.com;Uid=asdfghj;Pwd=qazwsxedc;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO etc.... ");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue( etc.... );
connection.Open();
int r = cmd.ExecuteNonQuery();
}
It failes on the connection.Open() instruction throwing an exception -> cannot connect to the server.
Any ideas please?
SqlConnection is a SQL Server client.
You need to download a MySql client from NuGet.
First download the MySQL Connector.
Make sure you add a reference to the DLL (+ set copy local to true !)
Add using MySql.Data.MySqlClient; on top of your class.
As for the Connection String, do not add http or www in front of server. As it will try to connect to apache (port 80) instead to MySQL. The default port of MySQL is 3306.
string connectionString = "Persist Security Info=False;database=qwertyui;server=qwertyuiop.com;Uid=asdfghj;Pwd=qazwsxedc;port=3306";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
string query = "INSERT INTO table VALUES (#parameter)";
connection.Open();
using (MySqlCommand cmd = new MySqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("#parameter", parameter);
cmd.ExecuteNonQuery();
}
}
If this is not working. Make sure MySQL allows remote access, if this is not the case, you can keep trying forever without any result.
First thing that comes to mind is that you will have to use a MysqlConnection and command.
http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlconnection.html
Is it a local database?
And if with all of above does not work try to get grant to all privileges(GRANT Syntax)!
Basically it will go something like:
GRANT ALL PRIVILEGES ON DBname.* to 'username'#'IPadress' IDENTIFIED BY 'password';

Categories

Resources