I have a problem with my writting to database and reading from database.
Here is my code:
MySqlConnection conn = new MySqlConnection(ConnectionString);
string ID = "";
MySqlCommand cmdRegister = new MySqlCommand("Insert into Players (username,password) values('"+"John"+"', '"+"johnisbest"+"')", conn);
cmdRegister.ExecuteNonQuery();
MySqlCommand cmdRead = new MySqlCommand("SELECT ID FROM Players WHERE username = '"+this.username+"';", conn);
MySqlDataReader reader = cmdRead.ExecuteReader();
conn.Open();
while (reader.Read())
{
ID = (string)reader["ID"];
}
conn.Dispose();
return ID;
It give me always error: Keyword not supported
Thanks for every help ;)
EDIT:
public MySQL(string IPaddress, string port, string username, string password, string database)
{
ConnectionString = "datasource=" + IPaddress + ";port=" + port + ";username=" + username + ";password=" + password + ";database=" + database + ";charse=utf_8";
}
sql = new MySQL("IP address to database", "3306", "username to database", "Here is my password to database", "name of my database");
ConnectionString = "datasource=" + IPaddress + ";port=" + port + ";username=" + username + ";pwd=" + password + ";database=" + database + ";charse=utf_8";
Tried to replace password with "pwd";
for me this work fine
Server=localhost;Database=testing;UID=root;password=testing;connect timeout=700;charset=utf8;pooling=true;Port=3306
Related
I'm a complete beginner in setting up databases dynamically. I found this code which is used to create a database:
String str;
SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master");
str = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\MyDatabaseData.mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%)" +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\MyDatabaseLog.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
My problem is that how should I prevent other applications from accessing the created database without specifying credentials like a username and password? I want to be able to do this programmatically (without using MS SQL Server Studio) since it is deployed along with the C# application on the customer's PC.
I have tried this for fun a long time ago, from MSDN. Give it a try:
public static void AddUsersToDatabase(string databaseserver, string databasename, string usertobeadded)
{
using (SqlConnection conn = new SqlConnection("server=" + databaseserver + "; database=" + databasename + "; User ID=WPDOMAIN\\spdev; Integrated Security=SSPI; password=Password123;"))
{
conn.Open();
string password = "Password123";
string sql = "CREATE LOGIN " + usertobeadded + " WITH PASSWORD = '" +
password + "'; USE " + databasename + "; CREATE USER " + usertobeadded + " FOR LOGIN " + usertobeadded + ";";
SqlCommand cmd = new SqlCommand(sql);
cmd.ExecuteNonQuery();
conn.Close();
}
}
i create small project that read data from sqlserver then insert into mysql table.
i want to users write SQL and mysql command into textbox.
here is my problem, when i run project the field that inserted into mysql table are: myReader["STableName"].ToString()
like this picture:
connections are fine, here is my code:
string address;
string username;
string password;
string database;
address = textBox1.Text;
username = textBox2.Text;
password = textBox3.Text;
database = textBox4.Text;
//MySql
string mysqladdress;
string mysqlusername;
string mysqlpassword;
string mysqldatabase;
mysqladdress = textBox7.Text;
mysqlusername = textBox8.Text;
mysqlpassword = textBox9.Text;
mysqldatabase = textBox10.Text;
//SQLCode
string sqlcmnd1;
string sqlcmnd2;
sqlcmnd1 = textBox5.Text;
sqlcmnd2 = textBox6.Text;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=" + address + ";" +
"Initial Catalog=" + database + ";" +
"User id=" + username + ";" +
"Password=" + password + ";";
try
{
conn.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand(sqlcmnd1, conn);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
string connectionString = #"server=" + mysqladdress + ";" + "username=" + mysqlusername + ";" + "password=" + mysqlpassword + ";" + "database=" + mysqldatabase + "";
MySqlConnection connection = null;
MySqlDataReader reader = null;
try
{
connection = new MySqlConnection(connectionString);
connection.Open();
string stm = sqlcmnd2;//here is my problem
MySqlDataAdapter dataAdapter = new MySqlDataAdapter();
dataAdapter.SelectCommand = new MySqlCommand(stm, connection);
DataTable table = new DataTable();
dataAdapter.Fill(table);
}
sqlcmnd2:
INSERT INTO test (CusCode,STableName,Date,ModdatZaman) VALUES ('" + myReader["CusCode"].ToString() + "','" + myReader["STableName"].ToString() + "','" + myReader["Date"].ToString() + "','" + myReader["ModdatZaman"].ToString() + "')
sqlcmnd1:
SELECT * FROM __TempUserCompRep__
Text from a textbox is considered as a full string it not replace the actual value of the variable .
You need to use prepared statement for that.
In textbox6 you write the command like this :
INSERT INTO test (CusCode,STableName,Date,ModdatZaman) VALUES (#CusCode,#STableName,#Date,#ModdatZaman)
After that in code, bind the parameter with variable from you actually want to take value.
For example:
MySqlConnection con = null;
try
{
string myConnectionString = "server=localhost;database=test;uid=root;pwd=root;";
con = new MySqlConnection(myConnectionString);
string CmdString = textBox6.Text.ToString();
MySqlCommand cmd = new MySqlCommand(CmdString, con);
cmd.Parameters.Add("#CusCode", MySqlDbType.VarChar, 50);
cmd.Parameters.Add("#STableName", MySqlDbType.VarChar, 50);
cmd.Parameters.Add("#Date", MySqlDbType.VarChar, 50);
cmd.Parameters.Add("#ModdatZaman", MySqlDbType.VarChar, 50);
cmd.Parameters["#CusCode"].Value = myReader["CusCode"].ToString();
cmd.Parameters["#STableName"].Value = myReader["STableName"].ToString();
cmd.Parameters["#Date"].Value = myReader["Date"].ToString();
cmd.Parameters["#ModdatZaman"].Value = myReader["ModdatZaman"].ToString();
con.Open();
int RowsAffected = cmd.ExecuteNonQuery();
if (RowsAffected > 0)
{
MessageBox.Show("Insert Query sucessfully!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con != null && con.State == ConnectionState.Open)
{
con.Close();
}
}
Note: I consider all four columns are varchar type in the database. you modify it according to your requirement
Hello Muhammad i would suggest you not to execute the sql commands from text box as there is a high chance of sql injection attacks , try to avoid as much you can , its a suggestion for more secured application
My SQLite query hangs then locks during my ExecuteNonQuery() in WriteToDB() below. It only seems to lock during the UPDATE and has no problem with the INSERT. This is only running in a single thread. When it hangs, I can see the journal being created in the SQLite database directory as if it keeps trying to write. It throws a SQLiteException with ErrorCode=5, ResultCode=Busy.
public String WriteToDB()
{
String retString = "";
//see if account exists with this email
String sql = "";
bool aExists = AccountExists();
if (!aExists)
{
sql = "INSERT INTO accounts (email, password, proxy, type, description) VALUES ('" + Email + "', '" + Password + "', '" + Proxy + "', 'dev', '" + Description + "');";
retString = "Added account";
}
else
{
sql = "UPDATE accounts SET password='" + Password + "', proxy='" + Proxy + "', description='" + Description + "' WHERE (email='" + Email + "' AND type='dev');";
retString = "Updated account";
}
using (SQLiteConnection dbconn = new SQLiteConnection("Data Source=" + Form1.DBNAME + ";Version=3;"))
{
dbconn.Open();
using (SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbconn))
{
sqlcmd.ExecuteNonQuery(); //this is where it locks. Only on update.
}
}
return retString;
}
//Test to see if Email exists as account
public bool AccountExists()
{
int rCount = 0;
String sql = "SELECT COUNT(email) FROM accounts WHERE email='" + Email + "' AND type='dev';";
using (SQLiteConnection dbconn = new SQLiteConnection("Data Source=" + Form1.DBNAME + ";Version=3;"))
{
dbconn.Open();
using (SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbconn))
{
rCount = Convert.ToInt32(sqlcmd.ExecuteScalar());
}
}
if (rCount > 0)
return true;
return false;
}
Oh man I feel dumb. I thought I posted all relevant code but all the code I posted works just fine. I had:
SQLiteDataReader dbReader = sqlcmd.ExecuteReader()
instead of
using (SQLiteDataReader dbReader = sqlcmd.ExecuteReader())
In another function. I thought it was an issue with the UPDATE because that was the place where the lock took place. Thanks for the responses and hopefully this reminds reminds everyone to use using() blocks with SQLite the first time!
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
string loginID = (String)Session["UserID"];
string ID = txtID.Text;
string password = txtPassword.Text;
string name = txtName.Text;
string position = txtPosition.Text;
int status = 1;
string createOn = validate.GetTimestamp(DateTime.Now); ;
string accessRight;
if (RadioButton1.Checked)
accessRight = "Administrator";
else
accessRight = "Non-administrator";
if (txtID.Text != "")
ClientScript.RegisterStartupScript(this.GetType(), "yourMessage", "alert('" + ID + "ha " + password + "ha " + status + "ha " + accessRight + "ha " + position + "ha " + name + "ha " + createOn + "');", true);
string sqlcommand = "INSERT INTO USERMASTER (USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES ("+ ID + "," + password + "," + name + "," + position + "," + accessRight + "," + status + "," + createOn + "," +loginID+ ")";
readdata.updateData(sqlcommand);
}
I am passing the sqlcommand to readdata class for execute..and its throw me this error..
ORA-00917: missing comma
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: ORA-00917:
missing comma.
The readdata class function code as below.
public void updateData(string SqlCommand)
{
string strConString = ConfigurationManager.ConnectionStrings["SOConnectionString"].ConnectionString;
OleDbConnection conn = new OleDbConnection(strConString);
OleDbCommand cmd = new OleDbCommand(SqlCommand, conn);
OleDbDataAdapter daPerson = new OleDbDataAdapter(cmd);
conn.Open();
cmd.ExecuteNonQuery();
}
Given that most of your columns are variable-length character, they must be enclosed in single quotes.
So, instead of:
string sqlcommand = "INSERT INTO myTable (ColumnName) VALUES (" + InputValue + ")";
You would, at minimum, need this:
string sqlcommand = "INSERT INTO myTable (ColumnName) VALUES ('" + InputValue + "')";
The result of the first statement, for an InputValue of "foo", would be:
INSERT INTO myTable (ColumnName) VALUES (foo)
which would result in a syntax error.
The second statement would be formatted correctly, as:
INSERT INTO myTable (ColumnName) VALUES ('foo')
Additionally, this code seems to be using values entered directly by the user, into txtID, txtPassword, and so on. This is a SQL Injection attack vector. Your input needs to be escaped. Ideally, you should use parameterized queries here.
This appears to be c#. Please update your tags accordingly.
At any rate, if it is .Net, here is some more information about parameterizing your queries:
OleDbCommand.Parameters Property
OleDbParameter Class
Try this
string sqlcommand = "INSERT INTO USERMASTER (USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES ('"+ ID + "','" + password + "','" + name + "','" + position + "','" + accessRight + "','" + status + "','" + createOn + "','" +loginID+ "')";
Concatenating the query and executing it is not reccomended as it may cause strong SQl Injection. Suppose if any one of those parameters contain a comma(,) like USERPWD=passwo',rd then query will devide it as passwo and rd by the comma. This may be a problem
It is recommended that you use "Parameterized queries to prevent SQL Injection Attacks in SQL Server" and hope it will resolve your issue.
Your code can be rewritten as follows
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
string loginID = (String)Session["UserID"];
string ID = txtID.Text;
string password = txtPassword.Text;
string name = txtName.Text;
string position = txtPosition.Text;
int status = 1;
string createOn = validate.GetTimestamp(DateTime.Now); ;
string accessRight;
if (RadioButton1.Checked)
accessRight = "Administrator";
else
accessRight = "Non-administrator";
if (txtID.Text != "")
ClientScript.RegisterStartupScript(this.GetType(), "yourMessage", "alert('" + ID + "ha " + password + "ha " + status + "ha " + accessRight + "ha " + position + "ha " + name + "ha " + createOn + "');", true);
string strQuery;
OleDbCommand cmd;
strQuery = "INSERT INTO USERMASTER(USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES(#ID,#password,#name,#position,#accessRight,#status,#createOn,#loginID)";
cmd = new OleDbCommand(strQuery);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#password", password);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#position", position);
cmd.Parameters.AddWithValue("#accessRight", accessRight);
cmd.Parameters.AddWithValue("#status", status);
cmd.Parameters.AddWithValue("#createOn", createOn);
cmd.Parameters.AddWithValue("#loginID", loginID);
bool isInserted = readdata.updateData(cmd);
}
rewrite your updateData data as follows
private Boolean updateData(OleDbCommand cmd)
{
string strConString = ConfigurationManager.ConnectionStrings["SOConnectionString"].ConnectionString;
OleDbConnection conn = new OleDbConnection(strConString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
I use this INSERT to add new record to database. But it can not show the Vietnamese in correct form. (Ex: Kh?ch s?n instead of Khách sạn).
How can I add "N" to the query in this case.
if (general.TestEmail.IsEmail(txt_Email.Text) == true)
{
//Insert dữ liệu vào database
email = txt_Email.Text;
MySqlCommand them_hotel = new MySqlCommand("INSERT INTO quan_li.hotel (name, star, address, province, phone, fax, email) VALUES (#name, #star, #address, #province, #phone, #fax, #email)");
them_hotel.CommandType = CommandType.Text;
them_hotel.Connection = conn_class.connection;
// them_hotel.Parameters.AddWithValue("#hid", txt_Hid.Text);
them_hotel.Parameters.AddWithValue("#name", txt_Ten.Text);
them_hotel.Parameters.AddWithValue("#star", txt_Sao.Text);
them_hotel.Parameters.AddWithValue("#address", txt_DiaChi.Text);
them_hotel.Parameters.AddWithValue("#province", txt_Tinh.Text);
them_hotel.Parameters.AddWithValue("#phone", txt_DienThoai.Text);
them_hotel.Parameters.AddWithValue("#fax", txt_Fax.Text);
them_hotel.Parameters.AddWithValue("#email", txt_Email.Text);
conn_class.OpenConnection();
them_hotel.ExecuteNonQuery();
conn_class.CloseConnection();
thanh_cong = "Đã thêm khách sạn thành công";
}
else
{
email_err = "Email không đúng định dạng \n";
}
Thank you very much for you help !
Solved:
I add Charset=utf8 to my connection string.
This is mine
public void Initialize()
{
server = "localhost";
database = "quan_li";
uid = "root";
password = "";
string connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";" + "Charset=utf8";
connection = new MySqlConnection(connectionString);
}