Hey guys I am using a connection string database set-up inside visual studios 2012.
I am trying to send data to the database there are no errors in the code but its not running, any help would be fantastic as i have been at it for a few hours now and need some sleep.
Thanks.
Default page code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace WebApplication1
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cs = new SqlConnection("Data Source = (LocalDB)\v11.0; Initial Catalog = Database1; Integrated Security = true");
SqlDataAdapter da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand("INSERT INTO Adopter (FIRSTNAME,LASTNAME) VALUES (#FIRSTNAME,#LASTNAME)", cs);
da.InsertCommand.Parameters.Add("#FIRSTNAME", SqlDbType.VarChar).Value = firstname.Text;
da.InsertCommand.Parameters.Add("#LASTNAME", SqlDbType.VarChar).Value = lastname.Text;
cs.Open();
da.InsertCommand.ExecuteNonQuery();
cs.Close();
}
protected void firstname_TextChanged(object sender, EventArgs e)
{
}
protected void lastname_TextChanged(object sender, EventArgs e)
{
}
}
}
SQL code
CREATE TABLE [dbo].[Adopter] (
[FIRSTNAME] VARCHAR (50) NOT NULL,
[LASTNAME] VARCHAR (50) NOT NULL,
);
I know it will be something simple... I just cant see it.
So, as we discussed in comments, it looks like the issue you have is with your connection string. You have:
SqlConnection cs = new SqlConnection("Data Source = (LocalDB)\v11.0;
Initial Catalog = Database1; Integrated Security = true");
What you need is:
SqlConnection cs = new SqlConnection("Data Source = .\SqlInstanceName;
Initial Catalog = Database1; Integrated Security = true");
The data source is the instance on your local machine, a hosted database or some other flavor of a Sql instance and the 'Initial Catalog' is the actual database name.
PS - I highly recommend that you look into the using keyword and wrap your command and connection objects with it so that when they fall out-of-scope, they are managed for you. It looks a bit like this when you use them:
using (SqlConnection cs = new SqlConnection())
{
// Some code can go here.
using (SqlCommand cmd = new SqlCommand())
{
// More code can go here.
}
}
I have a more comprehensive answer about it on this post. Happy coding!
Related
I can't get the form design to work my project compiles perfectly, but when I try to get click my button the file say key word not supported "allowloadlocalinfile"
I copied and paste what i thought was the connection string
server=localhost;userid=root;database=resume;persistsecurityinfo=True;allowloadlocalinfile=False;sslmode=None
but i get this error
here is my interface code
using System;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Windows.Forms;
namespace Resume2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=localhost;userid=root;database=resume;persistsecurityinfo=True;allowloadlocalinfile=False;sslmode=None");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO fields VALUES (#ResumeF_Name,#ResumeL_Name)",
con);
cmd.Parameters.AddWithValue("#ResumeF_Name", textBox1.Text);
cmd.Parameters.AddWithValue("#ResumeL_Name", textBox2.Text);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
I leave out the id column because it is set to auto_increment but he other to columns in my MySQL database "resume" table "fields" are ResumeF_Name and Resume_L_Name
now it's saying the connection string is server=localhost;user id=root;database=resume but still have a popup error
You have to use a connectionString for MySql instead of MS SQL.
Here are the main steps:
You have to add the nuget package "MySql.Data" to your project
Then you have to add the using using MySql.Data.MySqlClient(); to your code
You can then use this MySqlConnection cnn = new MySqlConnection("Server=localhost;Database=resume;Uid=root;Pwd=yourPassword;");
If you need some information about the connectionString for MySql. You can find out more information at this website: https://www.connectionstrings.com/mysql-connector-net-mysqlconnection/
I'm pretty new to SQL Databases & C# language, I can't add data to my SQL Database from my web application despite doing everything correctly? I'm currently training in Azure SQL & C# & have been using the following training video:
https://www.youtube.com/watch?v=POWm4EfU9bA
I'm using MS Visual Studio and MS SQL Server Management Studio, I'm also using Azure Web + SQL service and I have opened up the firewall allowing my client IP address through.
Can anyone work out, from my code, why I my data from my webform isn't being added to my database? Here is my coding which "apparently" adds data to my SQL database from the form located in my front end web application:
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace bluecitywebapplication
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == true)
{
Label1.Text = ("Great job!");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection stormconn = new SqlConnection("Server=tcp:bluecitydb.database.windows.net,1433;Initial Catalog=xxx;Persist Security Info=False;User ID=xxx;Password=xxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;");
{
SqlCommand insert = new SqlCommand("EXEC dbo.InsertFullname #Fullname", stormconn);
insert.CommandType = System.Data.CommandType.StoredProcedure;
insert.Parameters.AddWithValue("#Fullname", TextBox1.Text);
insert.Parameters.AddWithValue("#Address", TextBox2.Text);
insert.Parameters.AddWithValue("#Email", TextBox3.Text);
stormconn.Open();
insert.ExecuteNonQuery();
stormconn.Close();
if (IsPostBack)
{
TextBox1.Text = ("");
}
}
}
}
}
sorry, I apologize for the mistake, I thought that you are facing connection issue in your question. I read the code carefuly i found there is issue in the code of executing procedure. I updated the code.
protected void Button1_Click(object sender, EventArgs e)
{
using (var connection = new MySqlConnection("Server=tcp:xxxx.database.windows.net,1433;Initial Catalog=xxxx;Persist Security Info=False;User ID=xxxxx;Password=xxxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"))
{
MySqlCommand command = new MySqlCommand("InsertFullname", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new MySqlParameter("Fullname", TextBox1.Text));
command.Connection.Open();
var result = command.ExecuteNonQuery();
command.Connection.Close();
}
}
I caņ't seem to get around this error message: ExecuteNonQuery: Connection property has not been initialized
It refers to a cmd.ExecuteNonQuery();
I'm not really sure what is going on, maybe the insert is not correct, but here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace md2
{
public partial class Form2 : Form
{
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=MD2;Integrated Security=True;Pooling=False");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form2()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
cmd.Connection = cn;
}
private void button2_Click(object sender, EventArgs e)
{
if (izd_adr.Text != "" && izd_nos.Text != "") {
cn.Open();
cmd.CommandText = "insert into Publisher (pu_id, pub_name, adress) values ("+null+"'Elina', 'Kalnina')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Ir pievienots");
cn.Close();
new Form1().Show();
}
}
}
}
I followed a tutorial in how to do this, but I'm getting this error.
That Database looks like this:
This seems like a easy mistake somewhere, but is really frustrating...
You need to set the connection property on the command object:
cmd.Connection = cn;
An easier way to manage this is to let the SqlConnection create the command, which associates the SqlCommand with the SqlConnection: ie
cmd = cn.CreateCommand();
move cmd.Connection = cn; into the button click event. When you click the button currently, cmd has no connection property.
You must pass the SqlConnection to the SqlCommand, either with SqlCommand.Connection, pass it in the constructor or use CreateCommand().
I recommend creating a new SqlCommand and SqlConnection object when needed and refrain from caching them. SQL server does connection pooling anyway:
using (SqlConnection connection = new SqlConnection(...))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand("....", connection))
{
}
}
Change the Connection String as given below If you are using Compact 4.0 Database
SqlConnection cn = new SqlConnection(#"Data Source=|DataDirectory|\MD2.sdf");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
you can change the Provider Name according to you SQL Server Name.
and Move cmd.Connection = cn; into the button2_click event.
I agree with S. Laurijssen, and would like to emphasize that his example uses using blocks. Because SqlConnection and SqlCommand both implement IDisposable, each is automatically closed properly at the end of the block. My example put this in a class called Common.
My only, additional suggestion would be that you create a public static method that generates a SqlConnection object, opens it, and then returns the instantiated, opened connection. You can then do something like this:
using (SqlConnection cn = Common.GetConnection())
{
using (SqlCommand cmd = new SqlCommand("[your SQL command here]", cn))
{
}
}
With this pattern, you do not need to remember to open or close your SqlConnection, and your code is cleaner.
When I try to write in C# a connection to my app to my database, I build the application successfully in Visual Studio 2005 but when I run the site in debugger i get an error:
Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 118.
Here is the connection code that is giving the error:
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Server"].ConnectionString);
I have the connection string written correctly in my web.config, file so im clueless on what this remotely means. Im not sure if im missing anything. Any help appreciated. Here is my entire code for the section that might help:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Data.SqlClient;
public partial class RateAnalyzerPage: System.Web.UI.Page
{
protected void Search_Click(object sender, EventArgs e)
{
string IDnumber = mechantNumber.Text;
string selectSQL = "SELECT FROM Authors Where MID='"+ IDnumber +"'";
// SqlConnection con = new SqlConnection(#"Server=");
//SqlConnection con = new SqlConnection();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Server"].ConnectionString);
SqlDataReader reader;
try
{
con.Open();
SqlCommand cmd = new SqlCommand(selectSQL, con);
reader = cmd.ExecuteReader();
while (reader.Read())
{
QualVol.Text = reader["TotalVolume"].ToString();
}
reader.Close();
}
catch (Exception err)
{
}
finally
{
con.Close();
}
}
}
Let me know if im missing some data that would help.
Heres the connection string:
I've separated out and XML decoded the connection string value:
Data Source=Server;Initial Catalog=Odata;Integrated Security=True;MultipleActiveResultSets=False;Packet Size=4096;Application Name="Microsoft SQL Server Management Studio"User ID=Name;Password=PW
As you can see, you're missing a ; between Application Name and User ID. I'm not sure if that's the issue, but it's possible.
Your connection string use the Integrated Security=True, but the right syntax is
Integrated Security=SSPI; or Trusted_Connection=True so change it and remove the UserId and Password.
(or remove Integrated Security=True and leave UserID and Password)
Try to change something in your code.
protected void Search_Click(object sender, EventArgs e)
{
string IDnumber = mechantNumber.Text;
string selectSQL = "SELECT * FROM Authors Where MID=#num";
using(SqlConnection con = new SqlConnection
(System.Configuration.ConfigurationManager.ConnectionStrings
["Server"].ConnectionString))
{
SqlDataReader reader;
con.Open();
SqlCommand cmd = new SqlCommand(selectSQL, con);
cmd.Parameters.AddWithValue("#num", IDNumber);
reader = cmd.ExecuteReader();
while (reader.Read())
{
QualVol.Text = reader["TotalVolume"].ToString();
}
reader.Close();
}
}
Try to use the using statemend, this guarantees the disposing of your connection
Try to use parametrized query, this avoid Sql Injection attacks and quoting problems
Also SELECT requires a fields list or *
I think Jacob has it right. On a side note, don't do this:
string selectSQL = "SELECT FROM Authors Where MID='"+ IDnumber +"'";
This will lead to sql injection attacks, just like the one that was used to get yahoo user accounts last week.
Do this instead:
string selectSQL = "SELECT * FROM Authors Where MID=#ID";
cmd.Parameters.AddWithValue("#ID", IDnumber );
I'm using Visual Web Developer 2010 Express and SQL Server 2008 R2 Management Studio Express
Hey guys,
Pretty new at C# here. I'm trying to follow this C# ADO.NET tutorial (currently on step 2), and I'm stumped. I'm following all the steps, and everything makes sense to me in it, but whenever I try to debug, it does not show anything (in the sense of the c# methods not printing out a table from Northwind database onto my webpage) in WebApplication1's Default.aspx page.
For a while, I thought it was my connection string, conn, and I wasn't naming the "Data Source" attribute, which from my understanding is the name of the server I'm trying to connect to. It is all on a local machine, and I'm putting the correct server name.. I think. Server name is AZUES-221\JDOESQLSERVER
I'm properly escaping the backward slash, but I still don't know. Is there something in my coding that's flawed? Please help!
C# code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace WebApplication1
{
public partial class SqlConnectionDemo : System.Web.UI.Page
{
protected void Main(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=AZUES-221\\JDOESQLSERVER; Initial Catalog=Northwind; Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn); //passed the connection
rdr = cmd.ExecuteReader(); // get query results
while (rdr.Read()) //prints out whatever was
{ Console.WriteLine(rdr[0]); }//selected in the table
}
finally
{
if (rdr != null)// closes
{ rdr.Close(); }// the reader
if (conn != null)//closes
{ conn.Close(); }// the connection
}
}
}
}
Thanks in advance
As your example seems to be a WebProject try to put your code within Page_Load eventHandler. Afterwards you should try to print your data to the Debug window or to a control within your webPage.
using System;
using System.Data;
// and all the others ...
namespace WebApplication1
{
public partial class SqlConnectionDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=AZUES-221\\JDOESQLSERVER; Initial Catalog=Northwind; Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn);
rdr = cmd.ExecuteReader(); // get query results
while (rdr.Read()) //prints out whatever was
{
System.Diagnostics.Debug.WriteLine(rdr[0]); // or on the other hand
lblOutput.Text += rdr[0]; // as a "quick and dirty" solution!
}
}
finally
{
if (rdr != null)// closes
{ rdr.Close(); }// the reader
if (conn != null)//closes
{ conn.Close(); }// the connection
}
}
}
}
You may it find very useful to have a look at databound controls or just use another type of project (eg winForm, console, ...)
Create a Console application instead of the Web Application you have created.
Otherwise you will run into similar issues considering you are new to C# (or Visual Studio in general) AND considering the rest of the tutorial uses Console.WriteLine heavily.
Then you can use the same code as shown in the tutorial.
Additonally if you are concerned about the slash in the database server (it is a database server instance), you may wanna try this:
SqlConnection conn = new SqlConnection(#"Server=AZUES-221\JDOESQLSERVER;Database=Northwind;Trusted_Connection=True;");
Source: Connection Strings Reference
why would console.writeline show anything. you are not working on console.
in case just to see your output. use Response.writeline(rdr[0]);