Reputation: 6389
I need to rapidly write code to insert/update SQL data. In classic ASP/VBScript I could do that like below:
Set rs = Server.CreateObject("adodb.Recordset")
sql = "SELECT * FROM _table WHERE id=" & id
rs.Open sql, cn, 1, 3
If rs.recordcount = 0 Then
rs.AddNew
End If
rs("data") = data
rs.Update
rs.Close
What could be the nearest C# port of this code snippet? Thanks!
Upvotes: 2
Views: 1781
Reputation: 64467
Assuming MS-SQL:
using (SqlConnection conn = new SqlConnection("Connection String"))
using (SqlCommand comm = new SqlCommand("INSERT INTO MyTable (Name, Age) VALUES (@name, @age)", conn))
{
conn.Open();
comm.Parameters.AddWithValue("@name", "Adam");
comm.Parameters.AddWithValue("@age", 25);
comm.ExecuteNonQuery();
}
Connection string obviously needs fleshing out, and the parameterised SQL needs confirming, but this is the start of what you need.
You don't need to worry about closing as the using
statement does this for you.
Update: not knowing classic ASP very well, I should clarify that this code only does an insert and not an update, if you need to do an update, change the SQL to use the update syntax.
Upvotes: 3
Reputation: 81610
Hopefully this gets you started. Make a reference to the ADODB class:
ADODB.Connection cn = new ADODB.Connection();
cn.Open("Provider=etc...", null, null, 0);
ADODB.Recordset rs = new ADODB.Recordset();
String sql = "SELECT * FROM _table WHERE id=" & id;
rs.Open(sql, cn, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockOptimistic, -1);
if (rs.RecordCount == 0)
rs.AddNew;
rs("data") = data;
rs.Update();
rs.Close();
cn.Close();
Upvotes: 2