So I am trying to run a query in a database that searches the database table from a textbox input. My code is
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 Query
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void employeeBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.employeeBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.personnelDataSet);
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'personnelDataSet.employee' table. You can move, or remove it, as needed.
this.employeeTableAdapter.Fill(this.personnelDataSet.employee);
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
string connectionString = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";
private void btnSearch_Click(object sender, EventArgs e)
{
string commandText = "SELECT employeeID, name, position, hourlyPayRate " +
"FROM dbo.employee WHERE name LIKE '%'+ #Name + '%'";
using (SqlConnection connection = new SqlConnection(connectionString))
{
//Create a SqlCommand instance
SqlCommand command = new SqlCommand(commandText, connection);
//Add the parameter
command.Parameters.Add("#Name", SqlDbType.VarChar, 20).Value = textBox1.Text;
//Execute the query
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch
{
//Handle excepetion, show message to user...
MessageBox.Show("Error bitch!");
}
finally
{
connection.Close();
}
}
}
}
}
When I take the catch out I can see the error occurs at connection.Open(). The error takes a while to happen which makes me wonder whether there is an issue with string connectionString = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";
This is the error that I receive:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
You need to validate the connection string. If Open() is throwing an SqlException then the connection string is invalid. To enable you to establish the exact form of the connection string you require, take a look at connectionstrings.com.
As to why the exception is showing as unhanded, you need to 'consume' the exception as follows:
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception e)
{
// Handle excepetion, show message to user...
MessageBox.Show(e.Message);
}
I hope this helps.
Check this out:
string connectionString = "Server=.\InstanceName;Database=myDataBase;Integrated Security=True;";
Also
string commandText = "SELECT employeeID, name, position, hourlyPayRate
FROM dbo.employee WHERE name LIKE '%#Name%'";
try:
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User id=myUser;Password=myPAss;Connect Timeout=15;Integrated Security=false";
Try declaring your connection string inside the event.
An alternate method is to link your database through web.config as follows:
<connectionStrings>
<connectionString="Data Source=(localdb)\v11.0;Initial Catalog=DBName;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
And then the connection string can be as:
string cs = ConfigurationManager.ConnectionStrings["DBName"].ConnectionString;
Related
I am new to C# and need to create a little form application, that has two textboxes one that asks for a [File_ID] then when button is pressed send that number to a query and in another textbox display the output.
I have been playing around with it a bit, and have something like this. But it is not working. I am not sure if I should go on a different direction. I would REALLY appreciate your help.
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 testing
{
public partial class Form1 : Form
{
String str,dr;
SqlConnection con = new SqlConnection("Data Source=USHOU2016\\USFi;Initial Catalog=HOU_2016_Project;Integrated Security=True");
SqlCommand cmd;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
str = "SELECT TOP 1,[Sender Name],[Subject] from [OLE DB Destination] WHERE [CHAT #] ='" + textBox1.Text + "'";
cmd = new SqlCommand(str, con);
// dr = cmd.ExecuteReader();
con.Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox1.Text = cmd.ExecuteScalar().ToString();
}
}
}
Your SQL query syntax is wrong it should rather be below. You have a extra , after TOP 1 .. remove that
SELECT TOP 1 [Sender Name],[Subject] from [OLE DB Destination] WHERE...
Again in your button click you are just creating the command cmd = new SqlCommand(str, con); but never executing it. and just closing the connection.
In textBox2_TextChanged event handler you are trying to execute the query but connection has already gone. I think it's time you should consider reading about ADO.NET
This should do the trick. A couple of things to note:
since the button is executing your sql and populating the 2nd textbox, there's no need for the textbox_changed event
Using string concatenation to append your variables to your sql query is bad practice and makes your code susceptible to Sql Injection. Instead, parameterize your sql inputs as shown in the code below.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string query = "SELECT TOP 1,[Sender Name],[Subject] "
+ " from[OLE DB Destination] WHERE[CHAT #] = :chatId ";
using (SqlConnection con = new SqlConnection("Data Source=USHOU2016\\USFi;Initial Catalog=HOU_2016_Project;Integrated Security=True"))
{
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("chatId", textBox1.Text); //use Sql parameters to protect yourself against Sql Injection!
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
textBox2.Text = reader[0] + " " + reader[1]; //or however you want your output formatted
}
reader.close();
}
}
}
Sorry to be asking this I know there are many other questions and have tried to use the solutions provided but I just cannot get my code to work. Thanks for looking!
Connection String as shown in Properties:
Data
Source=(LocalDB)\v11.0;AttachDbFilename="C:\Users\Jacob\Documents\Visual
Studio
2013\Projects\WindowsFormsApplication2\WindowsFormsApplication2\ChatDB.mdf";Integrated
Security=True
Connection string in app.config:
Data
Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\ChatDB.mdf;Integrated
Security=True
Error: An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near the keyword 'User'.
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;
//NC-1 More namespaces.
using System.Data.SqlClient;
using System.Configuration;
namespace WindowsFormsApplication2
{
public partial class SignUp : Form
{
string connstr = ConfigurationManager.ConnectionStrings["WindowsFormsApplication2.Properties.Settings.ChatDBConnectionString"].ToString();
public SignUp()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void SubmitBtn_Click(object sender, EventArgs e)
{
string Name = NameText.Text;
string Pwd = PwdText.Text;
//make sure they have entered text
if (Name.Length > 0 && Pwd.Length > 0)
{
SqlConnection conn = new SqlConnection(connstr);
//NC-10 try-catch-finally
try
{
//NC-11 Open the connection.
conn.Open();
SqlCommand insert = new SqlCommand();
insert.Connection = conn;
insert.CommandText = "INSERT INTO [User] (Name,Password) VALUES ('" + Name + "','" + Pwd + "')";
insert.ExecuteNonQuery();
MessageBox.Show("Congrats!!!");
}
catch
{
//NC-14 A simple catch.
MessageBox.Show("User was not returned. Account could not be created.");
}
finally
{
//NC-15 Close the connection.
conn.Close();
}
}
//if no text make them enter
else
{
MessageBox.Show("Please enter Text in both fields.");
}
}
}
}
Again thank you for looking.
The problem is your SQL Query because you use a Reserved Keywords
Try to change your table name to tblUser.
I also suggest to use a parameterize query to prevent future SQL injection: (For Example)
#"INSERT INTO [User] (Name,Password) VALUES (#Name, #Password);"
I would like to know what's the problem, or your advice to connect to Oracle. I'm trying with this but when I try to insert values, it doesn't work.
I'm using the Visual Web Developer 2008 and when I add a database on Database Explorer connections, it's working. But when I try to connect via this connection string, it doesn't work. What am I missing?
I don't get an exception, so apparently it's working well. But this code apparently doesn't insert! The id column is a varchar(45). I created the table "test" just for testing purposes.
using System.Data;
using System.Data.OracleClient;
public partial class _Default : System.Web.UI.Page
{
//string oradb = "Data Source=localhost;User ID=root;Password=jesua;Unicode=True;";
String oracle = "User ID=root;Password=jesua;Unicode=True;Data Source=localhost;";
OracleConnection con = new OracleConnection();
public void Conectar() {
try
{
con.Close();
con.ConnectionString = oracle;
con.Open();
}
catch(Exception ex){
throw new Exception("No Conecto " + ex);
}
}
public void desconectar() {
// con.ConnectionString = oracle;
con.Close();
}
public void agregar() {
this.Conectar();
OracleCommand query = new OracleCommand("INSERT INTO testing (id) VALUES ('testing')");
query.ExecuteNonQuery();
desconectar();
}
protected void Button1_Click(object sender, EventArgs e)
{
try {
agregar();
}
catch(Exception ex){
Console.Write("No agrego " + ex);
}
TextBox1.Text = "Conected";
}
}
--------------------------UPDATE------------------
So,
i found the way to do that,
i hope anyone here can use this code in a future...
This code creates the connection betwen Oracle and asp.net C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Oracle.DataAccess.Client; // ODP.NET Oracle managed provider
using Oracle.DataAccess.Types;
namespace proyecto
{
public partial class WebForm1 : System.Web.UI.Page
{
public void dbconnect() {
string oradb = "Data Source=localhost;User ID={Yoir ID};Password={Your Password};";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO TESTING(id) VALUES ('valor')";
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
Console.Write("Record not inserted");
else
Console.Write("Success!");
conn.Dispose();
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
this.dbconnect();
}
}
}
Good Luck!
The connection string that works for me is
connectionString="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1522))
(CONNECT_DATA=(SERVICE_NAME=XE)));User Id=system;Password=pass;"
providerName="Oracle.DataAccess.Client"/>
It seems that you are missing the Service Name and Provider Name. You can find the service name in tnsnames.ora file which will be in your installation directory. Also make sure you have installed ODP.NET for Oracle 11g correctly, added reference to the Oracle.DataAccess.dll into your project and add the Provider Name in the connection string.
i have a problem with this c# code. I need to connect it to mysql, localhost database, Please give me the correct code to [connetionString = "Data Source=ServerName;Initial Catalog=root;User ID=root;Password="; ] connect to the localhost.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn ;
**connetionString = "Data Source=ServerName;Initial Catalog=localhost;User ID=root;Password=";**
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
It should look a little more like this:
connetionString = "Data Source=localhost;Initial Catalog=<Name of the Database>;User ID=root;Password=";
The data source property is where you put the network location, the initial catalog is the name of the database (in mysql).
Edit:
However, I believe you'll need the mysql libraries, which I notice you're not using at the beginning.
Get them from here: http://dev.mysql.com/downloads/connector/net/
The Data.SqlClient namespace is typically how you'd connect to MSSQL.
it seems you have tagged MySql connection, so preferably you want to use the mysql connection. Which you can download / install here: http://dev.mysql.com/downloads/connector/net/
Also it is wise to use the try-catch-finally approach. So that when the connection opens, and some exception occurs, the connection will always close afterwards.
As another addition, you could put the connectionstring in an App.Config or Web.Config so that you have the connectionstring available in all your files, and only have to adjust it in one place.
hope this will help you
using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient; //using the mysql dll
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=localhost;Initial Catalog=myDb;User ID=MyUser;Password=MyPass";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
MessageBox.Show(ex.Message); //shows what error actually occurs
}
finally
{
cnn.Close();
}
}
}
}
You are using System.Data.SqlClient in your connection which I think used for SQL Server. Your connection string is also not for MySQL Database. Try this one.
using System.Data.Odbc;
string connectionString = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=localhost;
DATABASE=dbname; UID=myuserid; PASSWORD=mypassword;OPTION=3; POOLING=false;";
OdbcConnection DBCon = new OdbcConnection(connectionString);
if (DBCon.State == ConnectionState.Open)
{
DBCon.Close();
}
DBCon.Open();
MessageBox.Show ("Connection Open ! ");
DBCon.Close();
Change the ODBC Driver version depending on what you are using.
Change the DATABASE, UID and PASSWORD value.
Here is the code you need
private void btnConnect_Click(object sender, EventArgs e)
{
string MyConStr = "Server=localhost;Database=YourDB;Username=YourUsername;Password=YourPassword";
MySqlConnection conn = new MySqlConnection(MyConStr);
conn.Open();
if (conn.State == ConnectionState.Open)
{
MessageBox.Show("Connection Opened Successfully");
conn.Close();
}
else
{
MessageBox.Show("Error Connecting to DataBase");
}
}
I have created a database using SQL Server Management Studio and am now trying to edit that database using Visual Studio Express 2012. I have connected the database to Visual Studio and can see my database but I have not been able to edit the database stored in Management Studio using Visual Studio. I have created a form and am trying to insert what is entered into textbox1 into a specific cell on my database after the user defines the column name and row (using the primary key in my DB) with textbox2 and textbox3. What code can I use to perform this action? So far I have had no luck. Thank you in advance for you help.
This is my current 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;
using System.Data.Sql;
using Microsoft.SqlServer.Server;
using System.Data.Linq;
using System.Data.Linq.Mapping;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection myConnectionString = new SqlConnection("Data Source=Server Catalog=DataBase;Integrated Security=True");
SqlCommand command = new SqlCommand();
private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection dbConnection = new SqlConnection()) // the "using" construct will close and dispose of the connection
{
dbConnection.ConnectionString = ("Data Source=Server ;Initial Catalog=Database;Integrated Security=True");
dbConnection.Open();
maskedTextBox1.Clear();
dateTimePicker1.Value = DateTime.Now.AddDays(0);
comboBox1.SelectedIndex = -1;
String username = comboBox2.Text;
using (SqlCommand command = new SqlCommand("INSERT INTO [Table Name] (Column Name) VALUES ([Parm1])", dbConnection))
{
command.Parameters.AddWithValue("Parm1", username);
command.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
//Close the Window
this.Close();
}
private void label4_Click(object sender, EventArgs e)
{
}
private void comboBox1_DataSourceChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
myConnectionString.Open();
MessageBox.Show("Sql is connected");
myConnectionString.Close();
}
}
}
The VALUES clause should specify a parameter and that parameter should be specified when adding the parameter value. Try substituting the following:
String sqlquery = "INSERT INTO [Man Power] ([Person_Performing_Phase_2]) VALUES ([Parm1])";
SqlCommand command = new SqlCommand(sqlquery, con);
command.Parameters.AddWithValue("Parm1", username);
EDIT
Your connection string is incorrectly formed. I believe the following format is appropriate for your current needs:
String myConnectionString = Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
I would use the following code for inserting data, which opens and closes the connection for each operation. Note the "command.ExecuteNonQuery" statement - its omission is why your insert failed to work - although I am unsure why opening the connection did not throw an error.
private void button3_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection dbConnection = new SqlConnection()) // the "using" construct will close and dispose of the connection
{
dbConnection.ConnectionString = myConnectionString;
dbConnection.Open();
maskedTextBox1.Clear();
dateTimePicker1.Value = DateTime.Now.AddDays(0);
comboBox1.SelectedIndex = -1;
String username = comboBox2.Text;
using (SqlCommand command = new SqlCommand("INSERT INTO [Man Power] ([Person_Performing_Phase_2]) VALUES ([Parm1])", dbConnection))
{
command.Parameters.AddWithValue("Parm1", username);
command.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
You should also remove all other _Click methods and replace the connection and command statement with the myConnectionString assignement.