ASP .net C# SqlConnection Error - c#

I have a window hosting in 1and1.com. I try to connect the database with following code, but I get the error message. You can view error message here http://www.s499993321.onlinehome.us/Default.aspx
Does any one know happen? How to connect the database?
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection("Server=localhost; Database=db500148144; User Id=dbo500148144; Password=12345abc"))
{
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM people", cn);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
rdr.Read();
Response.Write(rdr[0].ToString());
}
// Response.Write("How");
}

If SQL server is on the same machine use
SqlConnection cn = new SqlConnection(#"Server=.\MSSQLSERVER2012; Database=db500148144; User Id=dbo500148144; Password=12345abc")
MSSQLSERVER2012 is the instance name. One way to find out the name is by opening services.msc and checking the name of the sql server service running on your machine. for me it was
"SQL server(MSSQLSERVER2012)"

There is issue in your web.config file, Remove CustomeErrro tag from web.config , and try.

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?

unable to insert data in sql database with c# even no error accur

hy I want to insert new record in my database but am unable to do this even code is fully error free, I added following code in my button click event
here is my code
SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
private void btn_Update_Click(object sender, EventArgs e)
{
string query="insert into users(Name,Password)values('ubaid','ali')";
cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
}
I mean insert query is not updating my database, even when I execute my query it return 2 not 0 which means query applied successfully,
not really an answer but the steps you need to take to see whats going on, so we can help you are a bit longer...
you will need to execute the following query, once in your sql management studio, and once in your program ... i suspect the result being different in both cases
select ##SERVERNAME, ##SERVICENAME, db_name(), SCHEMA_NAME()
on the code side please use this:
private void btn_Update_Click(object sender, EventArgs e)
{
// string query="insert into users(Name,Password)values('ubaid','ali')";
// cmd = new SqlCommand(query, con);
// con.Open();
// cmd.ExecuteNonQuery();
// MessageBox.Show("Record Updated Successfully");
// con.Close();
string query="select ##SERVERNAME, ##SERVICENAME, db_name(), SCHEMA_NAME()";
cmd = new SqlCommand(query, con);
con.Open();
using(var rdr = cmd.ExecuteReader())
{
rdr.read();
MessageBox.Show($"{rdr.GetString(0)}, {rdr.GetString(1)}, {rdr.GetString(2)}, {rdr.GetString(3)} ");
}
con.Close();
}
the result should show the name of the server, its instance name, the name of your DB and of the default schema you are using in both cases
example result for my testmachine would look like this:
srv9, MSSQLSERVER, testdb, dbo
expectation in your case:
you will get 2 different results which means that your sql management studio, where you are trying to check if your code did the right thing, is using a different server, instance, database or schema
with the provided information it will be possible to change the used connectionstring so both your clients work on the same database...

Open database into application c#

I have added a SQL Server .mdf database file to my C# application, but when I try to connect with this code, the program causes a connection error.
CODE:
DataSet data;
string con = "Data Source=dbinterno.mdf;";
string queryString = "Select * FROM Dati";
try
{
using (SqlConnection connection = new SqlConnection(con))
{
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(queryString, connection);
command.ExecuteNonQuery();
data = new DataSet();
adapter.Fill(data);
MessageBox.Show(data.ToString());
connection.Close();
}
}
catch
{
MessageBox.Show("\n Problemi di connessione al database");
}
The error is:
ERROR IMAGE
Here are a couple observations:
Your connection string will need to be modified. Try using
string con = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";
using Windows Authentication or this:
string con = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;"; using standard security, Source: connectionstrings.com. This should be managed some other way than in code as well. Desktop applications can be de-compiled, and if the password changes, you would need a rebuild. In a ASP.NET application, Microsoft advises to use a web.config file or in the windows registry using a custom subkey.
You will want to use ExecuteReader() for a SELECT statement as ExecuteNonQuery() will not return a result set. See this answer that describes the differences in the types of SQL Server methods
you don't need connection.Close();, the using statement will handle that.

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 = "";
}

Categories

Resources