SQL Server 2012 Error 26 - c#

I downloaded SQL Server 2012 Express. Using http://www.mssqltips.com/sqlservertip/2694/getting-started-with-sql-server-2012-express-localdb/. I created a local database. Now when I tried to connect to that database using Visual Studio 2010 it throws me error 26
Here is my code:
using(SqlConnection connectionString = new SqlConnection(#"Server=(localdb)\SQLEXPRESS;database=master;Trusted_Connection=True;")
{
connectionString.Open(); //error 26
sql = "insert into Main ([Cable Length1], [Cable Length2]) values(#3',#5')";
using (SqlCommand cmd = new SqlCommand(sql, connectionString))
{
cmd.Parameters.AddWithValue("#3'", 1);
cmd.Parameters.AddWithValue("#5'", 2);
cmd.ExecuteNonQuery();
}
}
Also, I am able to login through SQL Server Management Studio 2012. Can anyone tell me what am I missing?

Ignoring all the other problems1, you should make up your mind as to whether you're using SQL Server LocalDB or not. I am highly doubtful you've made a private LocalDB instance called SQLEXPRESS.
You likely want something along the lines of:
new SqlConnection(#"Server=(localdb)\v11.0;Trusted_Connection=True;")
Or
new SqlConnection(#"Server=.\SQLEXPRESS;Trusted_Connection=True;")
1 being the following:
Your SqlConnection is called connectionString.
Parameters with quotes in their names.
Using master and then trying to insert into a table called Main. System databases are for the system. You are not the system.
I'd expect to see something along the lines of:
using (var connection = new SqlConnection(#"Server=(localdb)\v11.0;Database=MyDatabaseName;Integrated Security=true;")
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO [Main] ([Cable Length1], [Cable Length2]) VALUES(#3, #5)";
command.Parameters.AddWithValue("#3", 1);
command.Parameters.AddWithValue("#5", 2);
command.ExecuteNonQuery();
}
}

I got the solution: Make sure you are connected to Database and when you launch sql management studio under server name-->select browse for more-->select database engine and then select your local database. You should see the Green Icon and then you do get connected. Thanks for the help guys!

Related

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());
}

Application keep old sql connection when switch database (C#)

I have two SQL Server databases, server name are sql1 and sql2.
When I switch database from sql1 to sql2 (using HaProxy), my application still keeps the old SQL connection to server sql1.
However, other applications (using Linq-to-SQL) can get the new SQL connection to sql2.
Please see my code below that's I using to get connection to SQL Server:
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString))
{
using (SqlCommand command = new SqlCommand())
{
conn.Open();
//do something...
conn.Close();
return data;
}
}
What's my problem? How can I resolve this? Thanks!
You need to know the HAProxy listen configuration, maybe your HAProxy has exceptions programmed, or the redirection only works if you use an specific IP address destination or come from an specific IP range. Please compare the connections string used in each case.
https://www.stevefenton.co.uk/2016/11/load-balancing-microsoft-sql-server-with-haproxy/

Unable to execute script from c# using smo

I have developed a C# Windows application in which I need to create a database on client machine for which I have created a script file and installed SQL Server 2008 R2 on client machine.
But when I execute script from my code it always shows an error:
Failed to connect database.
I have added referenced the SMO assemblies from
C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies\Microsoft.SqlServer.Smo.dll
And my code is :
string sqlConString = #"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=mydatabase;Data Source=(local)";
FileInfo file = new FileInfo(dbPath);
string script = file.OpenText().ReadToEnd();
SqlConnection con = new SqlConnection(sqlConString);
Server server = new Server(new ServerConnection(con));
server.ConnectionContext.ExecuteNonQuery(script);
file.OpenText().Close();
How about something like this:
using (SqlConnection cnn = new SqlConnection(sqlConString))
{
var cmds = File.ReadAllText(#"path\to\file").Split(new string[] { "GO" },
StringSplitOptions.RemoveEmptyEntries);
cnn.Open();
foreach (var cmd in cmds)
{
using (SqlCommand cmd = new SqlCommand(cmd, cnn))
{
cmd.ExecuteNonQuery();
}
}
}
With this approach you get what you want, the script gets executed, but you don't have to use the slow and bloated SMO interface. Further, you're leveraging the using statement so you don't have to worry about unmanaged resources being left open.
Now, to address the failed to connect to database..., which I clearly missed the first time I read it, if that's happening that means this:
Initial Catalog=mydatabase;Data Source=(local)
is likely not right. And if it is, your server may not be accepting Windows Authentication.
I don't know the setup of your local machine, but it's likely that the server is (local)\SQLEXPRESS.

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 '#' .

Connection String Problem Oracle .Net

I am new to oracle and am trying to simply connect to an oracle db, but I am not sure where to find the proper credentials to put in the connection string. I simply downloaded and install oracle express edition on my machine, then installed the .Net references. My simple code is here:
string oradb = "Data Source=XE;User Id=hr;Password=hr;";
OracleConnection conn = new OracleConnection(oradb); // C#
try
{
conn.Open();
string sql = "SELECT FIRST_NAME FROM EMPLOYEES WHERE EMAIL='SKING'"; // C#
OracleCommand cmd = new OracleCommand(sql, conn);
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader(); // C#
dr.Read();
//label1.Text = dr["dname"].ToString(); // C# retrieve by column name
label1.Text = dr.GetString(0).ToString(); // return a .NET data type
//label1.Text = dr.GetOracleString(0).ToString(); // return an Oracle data type
}
catch (OracleException ex)
{
label1.Text = ex.Message;
}
finally
{
conn.Close();
}
I am getting a TNS:could not resolve the connect identifier specified exception. Its probably because my connection string is wrong is what I am guessing. I cannot even go to the Server Explorer dialog in Visual Studio and test a connection correctly to my oracle db.
What steps do I need to take to figure out the proper credentials to plug into my connection string?
Or wording it like this....
If you were going to install oracle express on your machine, then connect to a .Net app what steps would you take to set up the connection string?
Maybe it is looking for a data source defined in a tnsnames.ora file called XE.
Try the Easy Connect naming method in the Express edition. It enables application clients to connect to a database without using any configuration files, simply by specifying the data source attribute through syntax shown below:
user id=hr;password=hr;data source=hr-server
user id=hr;password=hr;data source=hr-server:1521
user id=hr;password=hr;data source=hr-server:1521/XE
Replace hr-server with the dns name or ip of your machine.

Categories