简体   繁体   中英

C# to database (textboxes)

I want to use my textboxes to send data to my database.

The problem is that he doesn't know loonberekening.tblWerknemer , I always get

incorrect syntax near 'tblWerknemer'

Here is a picture of my tables: http://gyazo.com/1a92845f51f56ef37e9ae3adf3f23a7c

string database = (@"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\gip_stap_2\loonberekening.mdf;Integrated Security=True;Connect Timeout=30");
string werknemergegevens = "insert into loonberekening.tblWerknemer (naam,voornaam) values ('"+txtNaam.Text+"','"+txtVoornaam.Text+"');";
SqlConnection cnnLoonberekening = new SqlConnection(database);
SqlCommand scmdLoon = new SqlCommand(werknemergegevens, cnnLoonberekening);
SqlDataReader check;

try{
    cnnLoonberekening.Open();
    check = scmdLoon.ExecuteReader();
    MessageBox.Show("Opgeslagen");
    while (check.Read())
    {
    }
}catch(Exception ex)
{
    MessageBox.Show(ex.Message);
}

Try "insert into loonberekening.dbo.tblWerknemer"

also as an aside look into parameterisation of the values.

Either add ;InitialCatalog=loonberekening to the end of the connection string to specify the database or add a schema name to the query: loonberekening.dbo.tblWerknemer .

  • There will be nothing to read back from an insert as you appear to be attempting
  • You need to use an SQLCommand to prevent what will happen if you run your code with a ' anywhere in the textbox. (SQL Injection)

尝试“插入到loonberekening.dbo.tblWerknemer”或仅“插入到tblWerknemer”,然后休息

Try rewrite the query as insert into dbo.tblWerknemer ... , because loonberekening is the database name and dbo.tblWerknemer is the actual table name

Also try to use parametrized query instead of directly passing values to prevent sql injection.

http://www.dreamincode.net/forums/topic/268104-parameterizing-your-sql-queries-the-right-way-to-query-a-database/

try this:

 string database = (@"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\gip_stap_2\loonberekening.mdf;Integrated Security=True;Connect Timeout=30");
string werknemergegevens = "insert into tblWerknemer (naam,voornaam) values (@Naam,@Voornaam)";
using(SqlConnection cnnLoonberekening = new SqlConnection(database))
{

SqlCommand scmdLoon = new SqlCommand(werknemergegevens, cnnLoonberekening);
    scmdLoon.Parameters.Add("@Naam",SqlDbType.VarChar).Value=txtNaam.Text;
    scmdLoon.Parameters.Add("@Voornaam",SqlDbType.VarChar).Value=txtVoornam.Text;
    scmdLoon.ExecuteNonQuery();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM