user3052409
user3052409

Reputation: 69

How to insert values into a database (Microsoft access)?

I'm trying to insert details of a user into a table called user in my database, however i think there's something wrong with how i wrote the query responsible in doing so.

Here's what I've done so far:

public static void addUser(string n, string s)
{
    OleDbConnection myConnection = GetConnection();
    string myQuery = "INSERT INTO user( Name, Surname) VALUES ( '" + n + " , " + s + "' )";
    OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);

    try
    {
        myConnection.Open();
        myCommand.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception in DBHandler", ex);
    }
    finally
    {
        myConnection.Close();
    }
}

Upvotes: 0

Views: 114

Answers (4)

Soner Gönül
Soner Gönül

Reputation: 98848

Well, you didn't tell us you get any error or not but using parameterized queries is always a better option. This kinf of string concatenations are open for SQL Injection attacks.

For example;

string myQuery = "INSERT INTO [user] ([Name], Surname) VALUES (@n, @s)";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
myCommand.Parameters.AddWithValue("@n", n);
myCommand.Parameters.AddWithValue("@s", s);

Also user and Name are reserved keywords on MS Access. You should use them with square brackets like [user] and [Name].

As a general recomendation, don't use reserved keywords for your identifiers and object names in your database.

Upvotes: 2

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

Problem : you are misusing single quotes.

Solution : you need to enclose the VARCHAR types in single quotes properly

Try This:

string myQuery = "INSERT INTO [user] ([Name],Surname) VALUES ( '" + n + "' , '" + s + "' )";

I suggest you to use Parameterised sql queries to avoid Sql Injection attacks

Try This: with Parameterised Queries

string myQuery = "INSERT INTO [user]([Name], Surname) VALUES (@name,@surname)";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
myCommand.Parameters.AddWithValue("@name",n);
myCommand.Parameters.AddWithValue("@surname",s);

Upvotes: 0

Thomas Weller
Thomas Weller

Reputation: 11717

The thing is that 'user' is a keyword for MS Access. You must put it in angle brackets: [user].

HTH Thomas

Upvotes: 0

Grant Winney
Grant Winney

Reputation: 66489

You're missing a couple apostrophes.

The way you've got it, instead of passing two parameters (i.e. 'one' and 'two'), you're passing a single parameter (i.e. 'one , two').

Try this:

string myQuery
    = "INSERT INTO user( Name, Surname) VALUES ( '" + n + "' , '" + s + "' )";

Upvotes: 0

Related Questions