I have the following method:
public void LottoTest(object sender, EventArgs e)
{
Dictionary<int, int> numbers = new Dictionary<int, int>();
Random generator = new Random();
while (numbers.Count < 6)
{
numbers[generator.Next(1, 49)] = 1;
}
string[] lotto = numbers.Keys.OrderBy(n => n).Select(s => s.ToString()).ToArray();
foreach (String _str in lotto)
{
Response.Write(_str);
Response.Write(",");
}
}
I would like to insert the contents of the lotto
array into a SQL Server 2008 database. The problem is i dont know how to do this at all. I have searched various ways insert database using C# and i find using a table adapter to create stored procedures is the best.
How do i utilise this table adapter to insert the data from the lotto
array?
I would start reading here:
That being said - here is how I would do it (depending how the numbers were passed in to me).
using System.Data.SqlClient;
namespace ConsoleApplication1
{
public class Lotto
{
public void InsertLottoNumbers(int[] lottonumbers)
{
var connectionstring = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
using (var con = new SqlConnection(connectionstring)) // Create connection with automatic disposal
{
con.Open();
using (var tran = con.BeginTransaction()) // Open a transaction
{
// Create command with parameters (DO NOT PUT VALUES IN LINE!!!!!)
string sql =
"insert into MyTable(val1,val2,val3,val4,val5,val6) values (@val1,@val2,@val3,@val4,@val5,@val6)";
var cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("val1", lottonumbers[0]);
cmd.Parameters.AddWithValue("val2", lottonumbers[1]);
cmd.Parameters.AddWithValue("val3", lottonumbers[2]);
cmd.Parameters.AddWithValue("val4", lottonumbers[3]);
cmd.Parameters.AddWithValue("val5", lottonumbers[4]);
cmd.Parameters.AddWithValue("val6", lottonumbers[5]);
cmd.ExecuteNonQuery(); // Insert Record
tran.Commit(); // commit transaction
}
}
}
}
}
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.