This is connection string
<add name="dbdatabase"
connectionString="Data Source=.\SQLTSRV02;Initial Catalog=movies;Integrated Security=True"
providerName="System.Data.SqlClient" />
Class connect:
protected SqlConnection sqlcon;
public bool open_connection(string connection = "dbdatabase")
{
sqlcon = new SqlConnection(#WebConfigurationManager.ConnectionStrings[connection].ToString());
try
{
if(sqlcon.State.ToString()=="open")
{
sqlcon.Open();
}
return true;
}
catch(Exception ex)
{
return false;
}
}
I can't get a connection to the database. Maybe I've made a mistake. Please help me find it
Thanks in advance
Looking from the connection string, i believe you are using a Local DB .
Add your DB to the visual studio-server explorer( under data connections) and then connect it. Then try debugging the code.
This line:
sqlcon = new SqlConnection(#WebConfigurationManager.ConnectionStrings[connection].ToString());
should be this:
sqlcon = new SqlConnection(#WebConfigurationManager.ConnectionStrings[connection].ConnectionString);
i.e. .ToString() is the wrong thing.
However, like #Guillaume, I'm confused by the #WebConfigurationManager part of it. It looks like it shouldn't compile...
Related
I am trying to connect to a database when I run my application I am getting the error "com.microsoft.sqlserver.jdbc.SQLServerException: The connection string contains a badly formed name or value".
I have tried changing some of the variables around but cannot figure out where my error is. Can anyone help?
try{
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
String dbURL = "jdbc:sqlserver://[myservername];databaseName=[databasename];user=[enteruserdbhere];password[enterpasswordhere];";
Connection conn = DriverManager.getConnection(dbURL);
Statement statement = conn.createStatement();
conn.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
Try removing the '[]' brackets from the connection string.
The link below shows examples of connection strings for jdbc https://learn.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15
You should remove the brackets [ ] for your connection URL.
String server = "localhost";
String dbName = "myDB";
String username = "root";
String pwd = "";
String dbURL = "jdbc:sqlserver://server;databaseName=dbName;user=username;password=pwd;";
Also import your jdbc driver to the project as well us in the Connection.java file
I've been working on a website using ASP.NET MVC, and I have this page in the website where you can directly send the a email form to a specific email address. Before I don't have database for the form, and it's working perfectly the form is sending without any problem but when I tried to add a database for it (cause I want the information to be save at the database at the same time send it) and tried to send it I keep on having this error:
But when I go to the other page it's working properly. I'm not really sure what the problem is cause I'm new with this kind of stuffs, but maybe the problem is related to this class:
public class RegisterRepository
{
//SqlTransaction transaction = null;
private SqlConnection con;
//To Handle connection related activities
private void connection()
{
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
con = new SqlConnection(constr);
}
public bool Register(TalentInfo model)
{
connection();
try
{
SqlCommand com = new SqlCommand("SP_INSERT_TALENT_INFO", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Talent_Name", model.Talent_Name);
com.Parameters.AddWithValue("#Talent_Email", model.Talent_Email);
com.Parameters.AddWithValue("#Talent_SelfPromotion", model.Talent_SelfPromotion);
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
if (i >= 1)
{
return true;
}
else
{
return false;
}
}
catch
{
return Register(model);
}
finally
{
con.Close();
}
}
}
I tried repairing my IIS 8.0 Express, (SSL Enable = True), and other solutions but it still doesn't work. Please someone help me. Thank you in advance.
This question has been addressed all over the web and I tried a lot of things without success. The SQL EXPRESS service is setup to accept local system account but the problem still exists.
This is my connection string:
<add name="PhoneTemplateChange" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Database=PhoneTemplateChange;Integrated Security=SSPI" />
I created a class to do database operations in the constructor I have
_connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["PhoneTemplateChange"].ConnectionString;
and a method in this class to insert data
public void AddNewChangeOrder(int operation, int targetExt)
{
using (SqlConnection con = new SqlConnection(_connectionString))
{
string sql = "INSERT into [dbo].ChangeOrder (operation, targetExt, dtrequested) VALUES (#operation, #targetExt, #dtrequested)";
using (SqlCommand cmd = new SqlCommand(sql))
{
try
{
cmd.Parameters.AddWithValue("#operation", operation);
cmd.Parameters.AddWithValue("#targetExt", targetExt);
cmd.Parameters.AddWithValue("dtrequested", DateTime.Now);
//con.CreateCommand();
con.Open();
//cmd.InitializeLifetimeService();
int rows = cmd.ExecuteNonQuery();
con.Close();
}
catch (SqlException e)
{
throw new Exception(e.Message);
}
}
}
I have played around with the connection string trying all different suggestions, also the commented code in the method above is what I tried to solve the problem. Still no luck!
I also changed the connection string I get two different exceptions this way
Database=PhoneTemplateChange
The above gives the exception in the title.
And the following gives the Exception "Cannot open Database PhoneTemplatechange.mdf requested by the login. Login failed for user 'mydomain\myusername'"
Database=PhoneTemplateChange.mdf
Any ideas?
You are missing the line of code where you specify that cmd uses con as it's connection. As a result the Command (cmd) has no connection, and con isn't associated with any command at all.
Add this line before executing:
cmd.Connection - con;
Alternatively (and better IMO) change your using statement as follows:
using (SqlCommand cmd = new SqlCommand(sql, con))
i'm using visual studio 2012 along with SQL SERVER 2008 express edition.
i wrote a C# program with the following code.
here "SQLExpress" is the instance name that i gave during installation...
private void btntest_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=SQLExpress;Database = Emp;Integrated Security=True";
try
{
con.Open();
MessageBox.Show("success");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
}
When i build this no errors are being shown..
when i run this no exceptions are being thrown..
but i cannot see any "MessageBox"..
what mistake am i doing here..
edit:
added the entire code.
#Oded
thanks for the help.my problem had been solved.
here's the code for connection string.
con.ConnectionString = #"Server=localhost\SQLExpress;Database = Emp;Integrated Security=True";
Replace your connection string
con.ConnectionString = "Server=SQLExpress;Database = Emp;Integrated Security=True";
with
connectionString="Data Source=SQLServerNameHere;Initial Catalog=DatabaseNameHere;Integrated Security=SSPI";
Use your configuartion instead of SQLServerNameHere and DatabaseNameHere.
try this
con.ConnectionString = "Data Source=your server name;User ID = your sql server username;Password=Your Sql Server Password;Initial Catalog=Your database name;Integrated Security=True";
The code below serves to change connection string in App.config at runtime, I found it here but this code did not work for me on Visual Studio 2010 and SQL Server 2008, I could not open the connection to the Northwind database.
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace MyNameSpace
{
public partial class FrmConnectionTest : Form
{
public FrmConnectionTest()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//Constructing connection string from the inputs
StringBuilder Con = new StringBuilder("Data Source=");
Con.Append(TxtServer.Text);
Con.Append(";Initial Catalog=");
Con.Append(TxtDatabase.Text);
Con.Append(";Integrated Security=SSPI;");
string strCon = Con.ToString();
updateConfigFile(strCon);
//Create new sql connection
SqlConnection Db = new SqlConnection();
//to refresh connection string each time else it will use previous connection string
ConfigurationManager.RefreshSection("connectionStrings");
Db.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ToString();
//To check new connection string is working or not
SqlDataAdapter da = new SqlDataAdapter("select * from employee");
DataTable dt = new DataTable();
da.Fill(dt);
CmbTestValue.DataSource = dt;
CmbTestValue.DisplayMember = "EmployeeID";
}
catch (Exception E)
{
MessageBox.Show(ConfigurationManager.ConnectionStrings["con"].ToString() + ".This is invalid connection", "Incorrect server/Database");
}
}
public void updateConfigFile(string con)
{
//updating config file
XmlDocument XmlDoc = new XmlDocument();
//Loading the Config file
XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement xElement in XmlDoc.DocumentElement)
{
if (xElement.Name == "connectionStrings")
{
//setting the coonection string
xElement.FirstChild.Attributes[2].Value = con;
}
}
//writing the connection string in config file
XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
}
}
Using Visual Studio 2010 and SQL Server2008, I got 2 errors for the next line:
SqlDataAdapter da = new SqlDataAdapter("select * from employee");
Error 1 The best overloaded method match for 'System.Data.SqlClient.SqlDataAdapter.SqlDataAdapter(System.Data.SqlClient.SqlCommand)' has some invalid arguments
Error 2 Argument 1: cannot convert from 'string' to 'System.Data.SqlClient.SqlCommand'
Is there any solution to this issue? Thank you.
The error is telling you that you are passing incorrect parameters to your SqlDataAdapter. I think the proper call would be:
SqlDataAdapter da = new SqlDataAdapter("select * from employee", Db);
Edit
It looks like you're creating your connection string from within your program, saving it to your config file, then reading it out of our config file right before you create your SqlDataAdapter. So, when you debug this line:
Db.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ToString();
Double check that Db.ConnectionString actually contains a connection string.
The other thing to do is open up your SQL Server Management Studio and confirm you can connect to the Northwind database from there. Including/alternatively, in Visual Studio, open your "Server Explorer" window and confirm you can create a Data Connection to Northwind by clicking Add Connection and then setting the connection property window to your server and dropping down the combobox to see if it populates with your databases:
Take a look at the available constructors of the SqlDataAdapter class.
There is no constructor overload that accepts just an SQL String.
You need to use one of the other overloads.
For example, there is one that needs an SQL String and a SqlConnection object.
To use it, change your code like this:
SqlDataAdapter da = new SqlDataAdapter("select * from employee", Db);
EDIT:
As BradRem already mentioned in his comment, try a different connection string.
If his example doesn't work for you, you can find more possible examples at http://connectionstrings.com/sql-server-2008.
Do you really have a database called Northwind on your server?
Does the Windows user on your current machine have permissions on the server to access the database? (that's what Integrated Security=SSPI means - your current Windows user is used to access the database!)