SQL in C# question
-
I'm doing some database in C# using MS SQL. Problem #1: Everytime i do a connection to my database, i have to copy and paste the code over and over. I heard of a way to put these code in the configuration file, but i don't know how to. Problem #2: I also heard of someway(interface, object) allowing me to do SQL query indirectly instead of passing the query string directly into the SqlCommand object. And, again, I don't know how to. Problem #3: Is there anyway i can pass in my sql query dynamically(ie, as a varible)? I just learn C# on my own, and having problem searching for things like this Please help me out! THANKS A BUNCH!!!
-
I'm doing some database in C# using MS SQL. Problem #1: Everytime i do a connection to my database, i have to copy and paste the code over and over. I heard of a way to put these code in the configuration file, but i don't know how to. Problem #2: I also heard of someway(interface, object) allowing me to do SQL query indirectly instead of passing the query string directly into the SqlCommand object. And, again, I don't know how to. Problem #3: Is there anyway i can pass in my sql query dynamically(ie, as a varible)? I just learn C# on my own, and having problem searching for things like this Please help me out! THANKS A BUNCH!!!
You should only need one
IDbConnection
instance to one database, and you can just reuse it every time (just open and close it). I am not sure what you mean by indirect query; however I think its good practice to use the interfaces rather than the specific providers as much as possible, as your provider might change. (i.e.IDbCommand cmd = new OldDbCommand("S...
). As for the queries, I keep mine as strings, not as string literals, and have them in a config file. That way I don't need to recompile every time i change a query. It also makes it easy to add on constraints on the query (cmd.CommandText = selectString + "WHERE Cust = " + custId.ToString()
). -
I'm doing some database in C# using MS SQL. Problem #1: Everytime i do a connection to my database, i have to copy and paste the code over and over. I heard of a way to put these code in the configuration file, but i don't know how to. Problem #2: I also heard of someway(interface, object) allowing me to do SQL query indirectly instead of passing the query string directly into the SqlCommand object. And, again, I don't know how to. Problem #3: Is there anyway i can pass in my sql query dynamically(ie, as a varible)? I just learn C# on my own, and having problem searching for things like this Please help me out! THANKS A BUNCH!!!
FYI, Problem #1 Where are you connecting from? Are you connecting from a web service? Windows Form? Asp.net? Problem #2 Problem #3 Read on on the .NET Documentation. Specifically with the SqlCommandBuilder.. It will automatically generate the SQL queries you require.. Its not as fast, to my understanding, as your own - danny