Hello I have good understanding on C and got a job for C# project but my knowledge on C# is poor. I started a project on C#. Project is billing and accounting software for resturants. I started doing login system. I used MSSQLocalDb.
In my login page i used ComboBox for UserID
Login page
When i click ComboBox it is empty
Problem
My youtube teacher's comboBox(Right one):
Right One
I don't know where is the problem please help dev friends...
I tried changing connection string didn't work
My connection code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Adisyon01
{
internal class cGenel
{
//public string conString = ("Server=(localdb)\\MSSQLLocalDB;Database=Restaurant2;Trusted_Connection=true");
public string conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Kerem Serinkan\\Restaurant2.mdf;Integrated Security=True;Connect Timeout=30";
public int _personelId;
}
}
My entry control code:
public bool personelEntryControl(string password,int UserId)
{
bool result = false;
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand("SELECT * FROM employee WHERE id=#Id AND PASSWORD=#password0", con);
cmd.Parameters.Add("#Id",SqlDbType.VarChar).Value = UserId;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = password;
try
{
if(con.State==ConnectionState.Closed)
{
con.Open();
}
result = Convert.ToBoolean(cmd.ExecuteScalar());
}
catch (SqlException ex)
{
string hata = ex.Message;
throw;
}
return result;
}
My SqlDataReader code:
public void personelGetbyInformation(ComboBox cb)
{
cb.Items.Clear();
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand("SELECT * FROM employee", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cPersoneller p = new cPersoneller();
p._personelId = Convert.ToInt32(dr["id"]);
p._personelGorevId = Convert.ToInt32(dr["TASKID"]);
p._personelAd = Convert.ToString(dr["NAME"]);
p._personelSoyad= Convert.ToString(dr["SURNAME"]);
p._personelParola= Convert.ToString(dr["PASSWORD"]);
p._personelKullaniciAdi = Convert.ToString(dr["NICKNAME"]);
p._personelDurum = Convert.ToBoolean(dr["STATUS"]);
cb.Items.Add(p);
}
dr.Close();
con.Close();
}
Related
I have a code that I use to login.
I call the data I get from textbox with a method and check the records with select query in the
database.
I call to relevant method , when I press the button.
private void btnGiris_Click(object sender, EventArgs e)
{
LoginBilgiler lb = new LoginBilgiler();
bool sonuc = lb.GirisKontrol(txtAd.Text, txtSifre.Text);
}
But I encounter errors in cmd.ExecuteReader the below.
public bool GirisKontrol(string ad,string sifre)
{
using (OracleConnection con = new OracleConnection(connectionString))
{
string query = String.Format("SELECT count(*) from Z_LABEL_USER where USERNAME=({0}) and PASSWORD=({1})", ad,sifre);
OracleCommand cmd = new OracleCommand(query, con);
con.Open();
OracleDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
kAdi = ad;
con.Close();
return true;
}
else
con.Close();
return false;
}
}
The table I use for the select query.
Oracle.ManagedDataAccess.Client.OracleException: 'ORA-01722: invalid
number'
Please, don't hardcode parameters in SQL; parametrize it instead:
public bool GirisKontrol(string ad, string sifre) {
//DONE: validate public methods' input
if (string.IsNullOrEmpty(ad))
return false; // or throw exception
else if (string.IsNullOrEmpty(sifre))
return false; // or throw exception
using (OracleConnection con = new OracleConnection(connectionString)) {
con.Open();
//DONE: no need to count all the entires, just check if there's at least one
//DONE: keep query readable
//DONE: paramterize queries
string query =
#"select 1
from Z_LABEL_USER
where USERNAME = :prm_UserName
and PASSWORD = :prm_Password";
using (OracleCommand cmd = new OracleCommand(query, con)) {
//TODO: this syntax can vary from library to library you use to work with Oracle
cmd.Parameters.Add(":prm_UserName", OracleType.VarChar).Value = ad;
cmd.Parameters.Add(":prm_Password", OracleType.VarChar).Value = sifre;
using (OracleDataReader dr = cmd.ExecuteReader()) {
if (dr.Read()) {
//TODO: Side effect : it changes instance's state. Do you really want it?
kAdi = ad;
return true;
}
}
}
}
return false;
}
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();
}
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
Is there any possibility to save data from local sdf database into text file in C# ? I don't have any idea how to do it and unfortunettly I don't have a lot of time.. each row of the database must be in new line of text file
You must do it manually (i.e. by code). MS SQL CE does not provide the import/export features that the SQL Server editions do.
this is from an old project of mine it works. just change the name of the table "tableProduit" with the name of your choice. if you run into problems ask ....
using System;
using System.Data.SqlServerCe;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Data;
namespace app
{
class Connexion
{
SqlCeConnection conn;
string connectionString;
string chemin;
public Connexion(string path,string password)
{
this.chemin = path;
connectionString = string.Format("DataSource={0}", this.chemin + ";Password="+password);
conn = new SqlCeConnection(connectionString);
}
public bool isConnected()
{
try
{
conn.Open();
}catch(SqlCeException e){
MessageBox.Show(e.ToString());
return false;
}
bool temp = false;
SqlCeDataReader dr;
SqlCeCommand cmd = new SqlCeCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM tableProduit";
dr = cmd.ExecuteReader();
if (dr.Read())
{
temp = true;
}
else
{
temp = false;
}
dr.Close();
conn.Close();
return temp;
}
public void writeData(string filepath,string filetype)
{
conn.Open();
SqlCeDataReader dr;
SqlCeCommand cmd = new SqlCeCommand();
SqlCeDataAdapter adpt = new SqlCeDataAdapter();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM tableProduit";
dr = cmd.ExecuteReader();
adpt.SelectCommand = cmd;
if (filetype == "txt")
{
TextWriter writer = new StreamWriter(filepath);
while (dr.Read())
{
writer.WriteLine(dr["codeBarre"] + ":" + dr["qte"]);
}
writer.Close();
}
else
{
//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
adpt.Fill(dt);
ds.Tables.Add(dt);
}
dr.Close();
conn.Close();
}
}
}
Edit : forget about the fileds writer.WriteLine(dr["codeBarre"] + ":" + dr["qte"]); change them to the names of your fields.good luck
Alright this is the first method
public static string srConnectionString = "server=localhost;database=myDB; "+
" uid=sa;pwd=myPW;";
And this is the second method
public static string srConnectionString = "server=localhost;database=myDB; "+
" integrated security=SSPI;persist security info=False; Trusted_Connection=Yes;";
Are there any performance difference or any other difference between these 2 connection strings?
Here my sql connection class any suggestion ?
using System;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
public static class DbConnection
{
public static string srConnectionString = "server=localhost; database=myDB; uid=sa; pwd=myPW;";
public static DataSet db_Select_Query(string strQuery)
{
DataSet dSet = new DataSet();
if (strQuery.Length < 5)
return dSet;
try
{
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
connection.Open();
using (SqlDataAdapter DA = new SqlDataAdapter(strQuery, connection))
{
DA.Fill(dSet);
}
}
return dSet;
}
catch
{
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
if (srConnectionString.IndexOf("select Id from tblAspErrors") != -1)
{
connection.Open();
strQuery = strQuery.Replace("'", "''");
using (SqlCommand command = new SqlCommand("insert into tblSqlErrors values ('" + strQuery + "')", connection))
{
command.ExecuteNonQuery();
}
}
}
return dSet;
}
}
public static void db_Update_Delete_Query(string strQuery)
{
if (strQuery.Length < 5)
return;
try
{
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(strQuery, connection))
{
command.ExecuteNonQuery();
}
}
}
catch
{
strQuery = strQuery.Replace("'", "''");
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("insert into tblSqlErrors values ('" + strQuery + "')", connection))
{
command.ExecuteNonQuery();
}
}
}
}
}
The performance difference is insignificantly small that it can be ignored. The authentication checks are
...performed only on login. The connection is not rechecked for each query. However with connection pooling, the connection is authenticated and reset many times, quite possibly for nearly every query
...the same as every file access and other activity involving the domain getting checked against Active Directory
FYI these two settings are the same (use one or the other):
integrated security=SSPI
Trusted_Connection=Yes