Using VS2010 with SqlClient and SQL Server 2012 - c#

I'm having a little problem inserting data from my application into my database. I do not get any errors while connecting or trying to insert into the database but data just doesn't get inserted. I use Visual Studio 2010 with C# and SqlClient and SQL Server 2012 Management Studio.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
<summary>
Summary description for Sources
</summary>
public class Sources
{
private string conString;
public int mSourceID;
public string mSourceName;
public int mActive;
public Sources()
{
conString = WebConfigurationManager.ConnectionStrings["dbconstring"].ConnectionString;
mSourceID = 0;
mSourceName = "";
mActive = 0;
}
public void insertData()
{
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Sources(SourceID, SourceName, Active) VALUES(#SourceID, #SourceName, #Active)", con))
{
cmd.Parameters.Add(new SqlParameter("SourceID", mSourceID));
cmd.Parameters.Add(new SqlParameter("SourceName", mSourceName));
cmd.Parameters.Add(new SqlParameter("Active", mActive));
}
}
catch (Exception Ex)
{
Console.WriteLine("Unable To Save Data. Error - " + Ex.Message);
}
}
}
}
And here is the button click event:
protected void btnOk_Click(object sender, ImageClickEventArgs e)
{
Sources src = new Sources();
src.mSourceID = 1;
src.mSourceName = "aboa";
src.mActive = 0;
src.insertData();
}
I've checked the debugger and do not get any errors thrown when I click the button, but when I check my table in my database it remains empty.

You need to execute your query using ExecuteNonQuery .check the below code.
public void insertData()
{
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Sources(SourceID, SourceName, Active) VALUES(#SourceID, #SourceName, #Active)", con))
{
cmd.Parameters.Add(new SqlParameter("SourceID", mSourceID));
cmd.Parameters.Add(new SqlParameter("SourceName", mSourceName));
cmd.Parameters.Add(new SqlParameter("Active", mActive));
cmd.ExecuteNonQuery();
}
}
catch (Exception Ex)
{
Console.WriteLine("Unable To Save Data. Error - " + Ex.Message);
}
}
}

You need to executenonquery because you are not retourning any data you are only inserting
and u also need the finally block to ensure that even if there is an exception the connection will be closed
public void insertData()
{
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Sources(SourceID, SourceName, Active) VALUES(#SourceID, #SourceName, #Active)", con))
{
cmd.Parameters.Add(new SqlParameter("SourceID", mSourceID));
cmd.Parameters.Add(new SqlParameter("SourceName", mSourceName));
cmd.Parameters.Add(new SqlParameter("Active", mActive));
cmd.ExecuteNonQuery();
}
}
catch (Exception Ex)
{
Console.WriteLine("Unable To Save Data. Error - " + Ex.Message);
}
finally
{
con.Close();
}
}
}

Related

How do I get around my ExecuteScalar returning null?

I am creating a basic registration page using ASP.NET websites and C# and am trying to link the logins to a database I have created in Visual Studio 2017 and am constantly getting the error -
'System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Data.Common.DbCommand.ExecuteScalar(...) returned null.
and cannot understand why, code below any help appreciated.
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.Configuration;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "SELECT * FROM [Table] WHERE UserName='" + TextBoxUN.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already exists, please enter a different username");
}
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "INSERT INTO Table (UserName,Email,Password,Country) values(#Uname ,#email , #password ,#country)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#Uname" , TextBoxUN.Text);
com.Parameters.AddWithValue("#email" , TextBoxEmail.Text);
com.Parameters.AddWithValue("#password" , TextBoxPass.Text);
com.Parameters.AddWithValue("#country" , DropDownListCountry.SelectedItem.ToString());
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
Response.Write("Registration Successful");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
}```
If you want to check if user exists, there's no need in ExecuteScalar() with value:
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
when user doesn't exist, com.ExecuteScalar() returns null and you have a problem.
Code
private static bool UserExists(string userName) {
if (null == userName)
return false;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString)) {
conn.Open();
//DONE: parametrized query
//DONE: 1 instead of * - we don't want all columns to be returned
string sql =
#"select 1
from [Table]
where UserName = #userName";
using (SqlCommand com = new SqlCommand(sql, conn)) {
com.Parameters.Add("userName", SqlDbType.VarChar).Value = userName;
// user exists if cursor is not empty (we have at least one record)
return com.ExecuteScalar() != null;
}
}
}
protected void Page_Load(object sender, EventArgs e) {
ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
if (IsPostBack && UserExists(TextBoxUN.Text))
Response.Write("User already exists, please enter a different username");
}

Update database field SQL in C#

I have tried many things, with no result. My question is, as the title says, how do I update a field in a database using SQL? Since I am a beginner with coding and SQL, I will copy my whole code below, not knowing what information you may need:
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 MySql.Data.MySqlClient;
using HPJFRMS;
namespace HPJFRMS
{
public partial class HomeFRM : Form
{
private string conn;
MySqlConnection connect;
string _naam = "";
Form _Loginfrm;
public HomeFRM(Form logFrom, string _name)
{
_Loginfrm = logFrom;
InitializeComponent();
lbWelkom.Text = "welkom " + _name;
_naam = _name;
}
private void HomeFRM_Load(object sender, EventArgs e)
{
tmCheck.Enabled = true;
}
private bool Todo_ophalen()
{
db_connection();
MySqlCommand cmdRead = new MySqlCommand();
cmdRead.CommandText = "SELECT `todo` FROM `user` WHERE `username` LIKE '" + _naam + "'";
cmdRead.Connection = connect;
MySqlDataReader tdOphalen = cmdRead.ExecuteReader();
if (tdOphalen.Read())
{
tbTodo.Text = tdOphalen.GetString(0);
connect.Close();
return true;
}
else
{
connect.Close();
return false;
}
}
private void db_connection()
{
try
{
conn = "Server=127.0.0.1;Database=users;Uid=root;Pwd=;";
connect = new MySqlConnection(conn);
connect.Open();
}
catch (MySqlException e)
{
throw;
}
finally
{
lbStatus.ForeColor = Color.Red;
}
}
private void btBewerk_Click(object sender, EventArgs e)
{
if (btBewerk.Text == "Bewerken")
{
tbTodo.ReadOnly = false;
btBewerk.Text = "Opslaan";
tmCheck.Enabled = false;
}
else
{
/* HERE COMES THE "UPDATE" CODE */
}
}
private void tmCheck_Tick(object sender, EventArgs e)
{
try
{
bool T = Todo_ophalen();
if (T)
{
lbStatus.ForeColor = Color.Green;
lbStatus.Text = "Online";
}
}
catch
{
lbStatus.ForeColor = Color.Red;
lbStatus.Text = "Offline";
}
}
}
}
There are different methods, you can use any of these.
Method 1: using simple SQL query
public void Update(Int UserId,String UserName )
{
SqlConnection con = new SqlConnection("Your Connection String");
con.Open();
string str = " UPDATE [dbo].[User] SET [UserName] = "+UserName +" WHERE [UserId] ="+ UserId+"";
SqlCommand cmd = new SqlCommand(str , con);
cmd.ExecuteNonQuery();
con.Close();
}
Method 2: using a stored procedure
First execute your stored procedure in database.
Example
CREATE PROCEDURE [dbo].[UpdateUser]
#UserId int,
#UserName varchar(25)
AS
BEGIN
UPDATE [dbo].[User]
SET [UserName] = #UserName
WHERE [UserId] = #UserId
END
public void Update(Int UserId,String UserName )
{
SqlConnection con = new SqlConnection("Your Connection String");
con.Open();
SqlCommand cmd = new SqlCommand("UpdateUser", con); //UpdateUser is the name of stored procedure you created
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("UserName ", UserName );
cmd.Parameters.AddWithValue("UserId", UserId);
cmd.ExecuteNonQuery();
con.Close();
}
Here is a sample method for an update:
public void UpdateUser(User userToUpdate)
{
try
{
string sqlStatement = #"UPDATE USERS " +
"SET DisplayName = #DisplayName, Username = #Username" +
"WHERE Id = #Id";
using (SqlConnectionconn = new SqlConnection("connection string here"))
using (SqlCommand cmd = new SqlCommand(sqlStatement, conn))
{
cmd.Parameters.Add(new SqlParameter("#Id", userToUpdate.Id));
cmd.Parameters.Add(new SqlParameter("#DisplayName", userToUpdate.DisplayName));
cmd.Parameters.Add(new SqlParameter("#UserName", userToUpdate.UserName));
cmd.ExecuteNonQuery();
}
}
catch (DbException ex)
{
throw ExceptionHandler.CreateSystemException(ex, ErrorStrings.DATABASE_ERROR);
}
}
This should get you started but you really need to read up on this subject as explaining the correct practices would be too long for an answer here.
this is maybe you need
MySqlConnection con = new MySqlConnection(conStr);
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand(con);
cmd.CommandText = "UPDATE table_name SET field_name_1 = ?param1, field_name_2 = ?param2 WHERE id = ?id";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("?param1", value1);
cmd.Parameters.AddWithValue("?param2", value2);
cmd.Parameters.AddWithValue("?id", value3);
cmd.ExecuteNonQuery();
}
catch (MySqlException ee)
{
MessageBox.Show(ee.Message);
}
finally
{
con.Close();
con.Dispose();
}

SqlException when querying database

when I developing just registration page this error occurred
error:An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
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.Configuration;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
String checkuser = "select count(*) from [UserData] where User Name='"+ TextBox1UN.Text +"'";
SqlCommand comm = new SqlCommand(checkuser,conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if(temp==1)
{
Response.Write("user allready exists");
}
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
String InserQuery = "insert into [UserData](UserName,Email,Password,Country)values(#Uname,#email,#pass,#country)";
SqlCommand comm = new SqlCommand(InserQuery, conn);
comm.Parameters.AddWithValue("#Uname", TextBox1UN.Text);
comm.Parameters.AddWithValue("#email", TextBox2EI);
comm.Parameters.AddWithValue("#pass", TextBox3PW);
comm.Parameters.AddWithValue("#country", DropDownList1cont.SelectedItem.ToString());
comm.ExecuteNonQuery();
Response.Write("Registration is succesful");
Response.Write("Administrator.aspx");
conn.Close();
}
catch (SqlException ex)
{
Response.Write("Error:"+ex.ToString());
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
}
aspx file:
<asp:SqlDataSource ID="SqlDataSourceRegistration"
runat="server"
ConnectionString="<%$ConnectionStrings:RegistrationConnectionString %>"
OnSelecting="SqlDataSourceRegistration_Selecting"
SelectCommand="SELECT * FROM [UserData]" >
</asp:SqlDataSource>
Your Query is not valid there is space between User Name and User is a keyword in sql. Your query should look like this
"select count(*) from [UserData] where UserName=#username";
Use Parameterized SQL
Add parameters to the command instead of concatenating values
comm.Parameters.AddWithValue("#username",TextBox1UN.Text);
A tip: Your code is very hackable / unsecure... because you put user input into the sql string you should use parameters instead.
You also have a space in your field name 'User Name' which I'm guessing is your issue so I put it as 'UserName'.
You should also put your code into a try catch statement so you can read the error.
try
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
using (SqlCommand command = new SqlCommand(
"SELECT COUNT(*) from [UserData] where UserName= #Name", connection))
{
// Add new SqlParameter to the command.
command.Parameters.Add("#Name", SqlDbType.NVarChar).Value = TextBox1UN.Text;
int temp = Convert.ToInt32(command.ExecuteScalar().ToString());
if(temp==1)
{
Response.Write("user allready exists");
}
}
}
catch (Exception ex)
{
// Display the exception's data dictionary.
foreach (DictionaryEntry pair in ex.Data)
{
Console.WriteLine("{0} = {1}", pair.Key, pair.Value);
}
}

Connect a C# Windows Form App to a MySQL Database on a Linux based server

I am working on an C# application which would use the remote MySQL database located in my website hosted on a Linux server with PHP & MySQL support.
I tried to connect directly to the MySQL database using MySql.Data.MySQLClient Reference, as a result, my program is throwing following exception :
"Unable to connect to any of the specified MySQL hosts."
I searched many tutorials but got no solutions... getting the same error.
Can anybody please tell me how to do this.
Please suggest any online links or tutorials or your own idea.
Please help me.
here's 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.Windows.Forms;
using MySql.Data.MySqlClient;
namespace mysq
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string conn = "Server = myserver;database = db ;uid = username ;password = pwd ;";
MySqlConnection con = new MySqlConnection(conn);
con.Open();
if (con.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand("Select * from table", con);
DataTable dt = new DataTable();
MySqlDataAdapter ad = new MySqlDataAdapter(cmd);
ad.Fill(dt);
dataGridView1.DataSource = dt;
}
}
catch (Exception)
{
throw;
}
}
}
}
Thanks in advance..
I've written an own class with functions for my mysql-connection.
First of all declare the server connection:
string ServerConnection = "Server=localhost;Port=1234;Database=YourDb;Uid=user;password=pass;"
This is how I select data:
public static void DB_Select(string s, params List<string>[] lists)
{
try
{
using(var conn = new MySqlConnection(ServerConnection))
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
using(var sqlreader = cmd.ExecuteReader())
while (sqlreader.Read())
{
if (sqlreader[0].ToString().Length > 0)
{
for (int i = 0; i < lists.Count(); i++)
{
lists[i].Add(sqlreader[i].ToString());
}
}
else
{
foreach (List<string> save in lists)
{
save.Add("/");
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error while selecting data from database!\nDetails: " + ex);
}
}
The call:
List<string> allRows = new List<string>();
DB_Select("SELECT field1 FROM table1 WHERE 1", allRows);
Notice: For every field you are selecting, you have to pass an own list which will be filled with the output.
For updating your database it would be quite the same function. You just wouldnt have to grad the output. Could look like this:
public static void DB_Update(string s)
{
try
{
using (var conn = new MySqlConnection(ServerConnection))
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
int numRowsUpdated = cmd.ExecuteNonQuery();
if(numRowsUpdated < 0)
{
MessageBox.Show("Warning DB-Contact: Affected_rows < 0!");
}
}
}
catch (Exception ex)
{
MessageBox.Show(String.Format("Updating database failed!\n\nSQL: {0}\n\nERROR: {1}",s,ex.Message));
}
}
You have to provide proper connection string in your program, i am suspecious you are passing proper IP address or hostname of the server where you hosted the database. As a first step try to ping the db server to make sure it is reachable from your machine. If it is reachable try as follows:
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
string conn = "Server =<provide proper ip address >;database = db ;uid = username ;password = pwd ;";
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
More details here : http://dev.mysql.com/doc/connector-net/en/connector-net-programming-connecting-open.html

C# ExecuteNonQuery "Connection must be valid and open."

I'm trying to add values into database, but every time I try to add some thing i get an error in the ExecuteNonQuery() with the message "Connection must be valid and open."
And I don't know what to do!!!
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 MySql.Data.MySqlClient;
namespace ClientesClinica
{
public partial class frmCadastro : Form
{
MySqlConnection conect = new MySqlConnection("server = localhost; user id = root; database = clientes; password = '';");
public frmCadastro()
{
InitializeComponent();
}
private void frmCadastro_Load(object sender, EventArgs e)
{
}
private void btnCancela_Click(object sender, EventArgs e)
{
Close();
}
private void btnSalvar_Click(object sender, EventArgs e)
{
int cod;
string nome;
string end;
int tel;
cod = Convert.ToInt16(txtCodigo.Text);
nome = txtNome.Text;
end = txtEndereco.Text;
if (txtNome.Text == "")
{
MessageBox.Show("Favor digitar o nome");
}
if (txtCodigo.Text == "")
{
MessageBox.Show("Favor digitar o código");
}
conect.Close();
MySqlCommand insere = new MySqlCommand();
insere.CommandText = "INSERT INTO cliente(cod, nome, endereco) Values(#cod + ,'#nome', '#end');";
insere.Parameters.AddWithValue("#cod", cod);
insere.Parameters.AddWithValue("#nome", nome);
insere.Parameters.AddWithValue("#end", end);
conect.Open();
insere.ExecuteNonQuery();// THE ERROR IS HERE!!!!
conect.Close();
MessageBox.Show("Salvo");
}
You need to open your connection and supply it to the command as per MSDN: SQLCommand
string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection); //<- See here the connection is passes to the command
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
Or for your usage:
conect.Open(); //<- Open Connection first
MySqlCommand insere = new MySqlCommand();
insere.Connection = conect; //<- Set the Commands connection
insere.CommandText = "INSERT INTO cliente(cod, nome, endereco) Values(#cod + ,'#nome', '#end');";
insere.Parameters.AddWithValue("#cod", cod);
insere.Parameters.AddWithValue("#nome", nome);
insere.Parameters.AddWithValue("#end", end);
insere.ExecuteNonQuery();
conect.Close();
this exception often raise cause of call the ExecuteNonQuery() method before connection opening
MySqlConnection con = new MySqlConnection(connection);
MySqlCommand command = con.CreateCommand();
command.CommandText="insert into stactoverflowtable (id,name) values('1','adil')";//suppose table name is stackoverflowtalbe
try
{
con.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
textBox1.Text = ex.Message;
}

Categories

Resources