...
using System.Data;
using System.Data.OleDb;
namespace accessloginapp
{
public partial class Ramen : Form
{
private OleDbConnection connection = new OleDbConnection();
public Ramen()
{
InitializeComponent();
connection.ConnectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\...\Users.accdb;Persist Security Info=False;";
}
private void btn_Save_Click(object sender, EventArgs e)
{
try{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText =
"insert into userdata (Username,[Password]) values('" +
txt_Username + "','" + txt_Password + "')";
command.ExecuteNonQuery();
MessageBox.Show("Users added and saved");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
}
}
I'm sorry if I do not understand much, I'm fairly to new to this. When I save data such as username and password in my application, the data is inserted as what I input but with added text, Example: I would send the username "Mark" to be inserted, but when I go to look at my database, it is put in as "System.Windows.Forms.TextBox, Text: Mark". How can I change this to only inserting the Username I Input?
You need to use Text property of textbox control, to fetch the actual text stored:-
command.CommandText = "insert into userdata (Username,[Password])
values('" + txt_Username.Text + "','" + txt_Password.Text + "')";
Apart from this please note your query is open for SQL Injection attack.
So, you should use Parameterized query something like this:-
command.CommandText = "insert into userdata (Username,[Password])
values(?,?)";
command.Parameters.Add("?",OleDbType.VarChar,20).Value = txt_Username.Text;
and similarly add parameter for #Password.
Related
I know plenty of people have these issues, and I've actually tried to implement some of the suggestions to my code, however I'm getting errors that just don't make sense to me. This is my first time implementing database calls to my code. Can someone please tell me what I'm doing wrong? The following error pops up: ERROR: Invalid object name 'Main'. This is actually triggered by my exception so at least something is working. Otherwise, I don't know what the issue is. On the DB end, I have (username VARCHAR, email VARCHAR and number NCHAR) Please see the code below
static string path = Path.GetFullPath(Environment.CurrentDirectory);
static string databaseName = "u_DB.mdf";
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=" + path + #"\" + databaseName + "; Integrated Security=True;";
private void button1_Click(object sender, EventArgs e)
{
// string query = "INSERT INTO UserInfo '" + textBox1.Text + "' and password = '" + textBox2.Text + "'";
string query = "insert into Main ([username], [email], [number]) values(#username,#email,#number)";
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = textBox3.Text;
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = textBox2.Text;
cmd.Parameters.AddWithValue("#number", SqlDbType.VarChar).Value = textBox1.Text;
int rowsAdded = cmd.ExecuteNonQuery();
if (rowsAdded > 0)
MessageBox.Show("Added to Database");
else
MessageBox.Show("Nothing was added");
}
}
catch (Exception ex)
{
MessageBox.Show("ERROR: " + ex.Message);
}
con.Close();
}
}
Firstly, as Chetan assumed, do you have a main table?
The syntax of the query you are using is :
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Furthermore,
AddWithValue(string parameterName, object value (<== The actual value to insert!));
in your case
AddWithValue("#number", textBox1.Text);
is enough.
I am trying to edit an Access DB_. For some reason I cannot insert anything. I believe my code is correct. The connection string is correct (though for security purposes I put a fake one for this post). At the end, I do not get the MessageBox like I am supposed to at the end of the function. Nothing was added to the Access DB either.
Any reason why this might be?
namespace TestBuild
{
public partial class Form1 : Form
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users...\Documents\TestDB.accdb");
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into table1 values('"+textBox1.Text+"','"+textBox2.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("record inserted successfully");
}
}
}
Suggestion - please consider refactoring your code as follows, and step through it, a line at a time, in the MSVS debugger:
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users...\Documents\TestDB.accdb";
private void Button1_Click(object sender, EventArgs e)
{
string sql = "insert into table1 values('" + textBox1.Text + "','" + textBox2.Text + "')";
OleDbCommand cmd= new OleDbCommand(sql);
using (OleDbConnection con = new OleDbConnection(connString)) {
cmd.Connection = conn;
try
{
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("record inserted successfully");
}
catch (Exception ex)
{
MessageBox.Show("ERROR" + ex.Message);
}
}
}
PS:
If you wanted to use prepared statements, you'd change your code to something like this:
string sql = "insert into table1 values(#param1, #param2)";
...
cmd.Parameters.AddWithValue("#param1", textBox1.Text);
cmd.Parameters.AddWithValue("#param1", textBox2.Text);
con.Open();
cmd.Prepare();
cmd.ExecuteNonQuery();
You can read more about techniques and guidelines for mitigating SQL injection here:
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
Here is another good article:
Best Practices for Using ADO.NET (MSDN)
private void okbtn_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Desktop\GameMuseumManagementSystem.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String Email = txtEmail.Text.ToString();
String Password = txtPassword.Text.ToString();
String my_query = "INSERT INTO Member(Member_Name,Member_Password,Member_Email)VALUES('" + Name + "','" + Email + "','" + Password + "')";
OleDbCommand cmd = new OleDbCommand(my_query, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfuly...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
}
I am coding for the member registeration for a guest to use it. I have 3 pieces of data, member_name, member_ID, and password. I coded this and I get an error. My Visual Studio is connected to my MS Access database via the tools, after I write this code, the data can't be stored in Access, what should I do now? Any suggestion?
I'm playing around with C# and Access databases trying to connect them and insert data through a web to the Access database, however I keep getting this:
"A first chance exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll"
on my output console and get nothing else.
not sure what I'm doing wrong but any help will do. Thanks
here's my code for getting the connection:
public partial class reg_Test : System.Web.UI.Page
{
private static OleDbConnection GetConnection()
{
String connString;
connString = #"Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\Users\Wisal\Documents\Visual Studio 2012\WebSites\WebSite3\test-db1.mdb";
return new OleDbConnection(connString);
}
here's my code for the submit button after user fill the text boxes Name and Surname:
protected void submitButtn_Click(object sender, EventArgs e)
{
OleDbConnection myConnection = GetConnection();
String TextBox1 = nameBox.Text;
String TextBox2 = snameBox.Text;
try
{
myConnection.Open();
Console.WriteLine("Connection Opened");
String myQuery = "INSERT INTO client values ([name], surname) values ('" + nameBox.Text + "','" + snameBox.Text + "');";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
myCommand.ExecuteNonQuery();
}
finally
{
myConnection.Close();
}
}
}
Change your query statement like below.
myConnection.Open();
Console.WriteLine("Connection Opened");
String myQuery = "INSERT INTO client([name], surname) values ('" + nameBox.Text "','"+ snameBox.Text + "');";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
myCommand.ExecuteNonQuery();
I currently have a little app sends a lot of different MySQL Queries to the server. My idea was to wrap the connection, the query and the read to a function with only the actual query as a parameter.
Here is what I got:
public static MySqlDataReader mySqlRead(string cmdText)
{
string connString = "server=" + ORVars.sqlServerAddr + ";port=" + ORVars.sqlServerPort + ";uid=" + ORVars.sqlServerUID + ";pwd=" + ORVars.sqlServerPass + ";database=" + ORVars.sqlServerDB + ";";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = cmdText;
try
{
conn.Open();
MySqlDataReader reader = command.ExecuteReader();
return reader;
}
catch (MySqlException)
{
throw;
}
}
I connect and send the query here:
private void btnLogin_Click(object sender, EventArgs e)
{
string username = txtLogin.Text;
string password = ORFunc.GetMD5Hash(txtPassword.Text);
MySqlDataReader orRead = ORFunc.mySqlRead("SELECT * FROM orUsers WHERE username = '" + username + "' AND pass = '" + password + "'");
while (orRead.Read())
{
MessageBox.Show(orRead["id"].ToString());
}
}
Works like a charm... BUT, as you can see above, the connection is never closed. When I add the conn.Close() behind the .ExecuteReader() the reader is empty and everything after return is of course useless.
Maybe it's a stupid question but I'm rather new to C# so please be generous, any hint is appreciated.
cheers,
PrimuS
I had a similar problem in JAVA recently, but I think the same will work for you. Essentially, you can create a class that represents a "SqlCall" object (or something). The class would have accessible members including the connection and the results. The ctor for the class would take in your query text.
Then, all you would have to do is create a new instance of that class, run the query in a method in that class (which would set and/or return the results), GET the results, and then when you are done, call close() on your class (which would then have to be coded such that it closes the connection held internally).
Technically, a better way to do this is to EXTEND the connection class itself, but as you are new to C#, I will not go into the details of doing so.
As I was writing the code below, I realized I may have not actually answered your question. But there's no point in backing out now, so here's what I have:
public class SqlCall {
private static connString = "server=" + ORVars.sqlServerAddr + ";port=" + ORVars.sqlServerPort + ";uid=" + ORVars.sqlServerUID + ";pwd=" + ORVars.sqlServerPass + ";database=" + ORVars.sqlServerDB + ";";
private MySqlConnection conn;
private MySqlCommand command;
private MySqlDataReader reader;
public SqlCall(String query) {
conn = new MySqlConnection(connString);
command = conn.CreateCommand();
command.CommandText = query;
}
public MySqlDataReader execute() throws Exception {
conn.Open();
reader = command.ExecuteReader();
return reader;
}
public void close() {
reader.close();
conn.close();
}
}
Your login code would be:
private void btnLogin_Click(object sender, EventArgs e) {
string username = txtLogin.Text;
string password = ORFunc.GetMD5Hash(txtPassword.Text);
SqlCall sqlcall = new SqlCall("SELECT * FROM orUsers WHERE username = '" + username + "' AND pass = '" + password + "'");
try {
MySqlDataReader orRead = sqlcall.execute();
while (orRead.Read())
{
MessageBox.Show(orRead["id"].ToString());
}
sqlcall.close();
} catch (Exception ex) {
// dostuff
}
}
The point is, unless you copy the data into a new datatable at the very beginning, you'll have to keep the connection open.
On a separate note, YOUR CODE IS PRONE TO SQL INJECTION. Don't know what that is? An example: if I said my username was ';DROP TABLE orUsers;--, then your entire user database would be gone. Look into stored procedures if you want a (very healthy) way around this.
You have difficulties because your idea works against the pattern expected by programs that connects to a database in NET Framework.
Usually, in this pattern you have a method that
INITIALIZE/OPEN/USE/CLOSE/DESTROY
the ADO.NET objects connected to the work required to extract or update data
Also your code has a serious problem called Sql Injection (see this famous explanation) because when you concatenate strings to form your command text you have no defense against a malicious user that try to attack your database
private void btnLogin_Click(object sender, EventArgs e)
{
string username = txtLogin.Text;
string password = ORFunc.GetMD5Hash(txtPassword.Text);
MySqlParameter p1 = new MySqlParameter("#uname", username);
MySqlParameter p2 = new MySqlParameter("#pass", pass);
string cmdText = "SELECT * FROM orUsers WHERE username = #uname AND pass = #pass"
DataTable dt = ORFunc.GetTable(cmdText, p1, p2);
foreach(DataRow r in dt.Rows)
{
Console.WriteLine(r["ID"].ToString());
}
}
public static DataTable GetTable(string cmdText, params MySqlParameter[] prms)
{
string connString = "server=" + ORVars.sqlServerAddr + ";port=" + ORVars.sqlServerPort + ";uid=" + ORVars.sqlServerUID + ";pwd=" + ORVars.sqlServerPass + ";database=" + ORVars.sqlServerDB + ";";
// This is the INITIALIZE part
using(MySqlConnection conn = new MySqlConnection(connString))
using(MySqlCommand command = new MySqlCommand(cmdText, conn))
{
// OPEN
conn.Open();
DataTable dt = new DataTable();
command.Parameters.AddRange(prms);
// USE
MySqlDataReader reader = command.ExecuteReader();
dt.Load(reader);
return dt;
} // The closing brace of the using statement is the CLOSE/DESTROY part of the pattern
}
Of course this is a generic example and in my real work I don't use very often these generic methods and prefer to write specialized data access code that return the base object needed to the upper layer of code