public void addintovisitor()
{
string companyname = (txtvisitor.Text.ToUpper());
DataSet result = new DataSet();
visitorcompany vc = new visitorcompany();
string Location1 = Convert.ToString(Session["location"]);
vc.checksamecompanyname(ref result, Location1);
for (int i = 0; i < result.Tables["details"].Rows.Count; i++)
{
if (companyname == result.Tables["details"].Rows[i]["Companyname"].ToString())
{
}
else
{
string strConn = Convert.ToString(ConfigurationManager.ConnectionStrings["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(
"INSERT INTO tblVisitorcompany ([CompanyName], " +
"[Location1]) " +
"VALUES(#CompanyName, #Location1)", conn);
cmd.Parameters.AddWithValue("#Companyname", companyname);
cmd.Parameters.AddWithValue("#Location1", Location1);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
My visitorcompany class:
public int checksamecompanyname(ref DataSet result, string Location1)
{
string strConn = Convert.ToString(
ConfigurationManager.ConnectionStrings
["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand
("select Companyname from tblVisitorcompany where Location1 ='" + Location1 + "'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
da.Fill(result, "details");
conn.Close();
//Return 0 when no error occurs.
return 0;
}
I am trying to search one row at a time to check whether the sql table got the same companyname. if there is already exisiting companyname, the program will do nothing. If this is a new companyname, the program will add companyname into the sql table. However, when adding new companyname, the program will add more than once. Can someone please help me to re-edit my program such that it only add one new companyname. Many thanks.
using( var connection = new SqlConnection( "my connection string" ) ) {
using( var command = connection.CreateCommand() ) {
command.CommandText = "SELECT Column1, Column2, Column3 FROM myTable";
connection.Open();
using( var reader = command.ExecuteReader() ) {
var indexOfColumn1 = reader.GetOrdinal( "Column1" );
var indexOfColumn2 = reader.GetOrdinal( "Column2" );
var indexOfColumn3 = reader.GetOrdinal( "Column3" );
while( reader.Read() ) {
var value1 = reader.GetValue( indexOfColumn1 );
var value2 = reader.GetValue( indexOfColumn2 );
var value3 = reader.GetValue( indexOfColumn3 );
// now, do something what you want
}
}
connection.Close();
}
dont use companyname as an argument of your insert command, since it is stays the same in for loop. Use result.Tables["details"].Rows[i]["Companyname"].ToString() instead:
...
cmd.Parameters.AddWithValue("#Companyname", result.Tables["details"].Rows[i]["Companyname"].ToString());
...
Check if the value exists, then add it if not.
A simple change in your code:
bool valueFound = false;
// check if the value exists
for (int i = 0; i < result.Tables["details"].Rows.Count; i++)
{
if (companyname == result.Tables["details"].Rows[i]["Companyname"].ToString())
{
// it exists so we exit the loop
valueFound = true;
break;
}
}
// we have looped all the way without finding the value, so we can insert
if(!valueFound)
{
string strConn = Convert.ToString(ConfigurationManager.ConnectionStrings["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(
"INSERT INTO tblVisitorcompany ([CompanyName], " +
"[Location1]) " +
"VALUES(#CompanyName, #Location1)", conn);
cmd.Parameters.AddWithValue("#Companyname", companyname);
cmd.Parameters.AddWithValue("#Location1", Location1);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
Off course you could check if the value exists in a more efficient way, but this should at least solve your specific problem.
Related
I have code using SqlBulkCopy to clone a lot of tables, it used to work before, but very weird, recently got exception
Received an invalid column length from the bcp client for colid
I have search this exception and still not solve my problem.
sqlBulkCopy.WriteToServer(reader) will raise this exception if a table has two continous columns which are both of type Char(1) or nvarchar(nn), and both have NULL. Sometime, changing the SqlBulkCopy.BatchSize makes it work, but many times, it will not.
After simplify, I have test case as follow, and it is reproduceable on two servers:
Create a table like below: (tested on SQL Server 2012 SP 4 and SQL Server 2016 SP2)
IF OBJECT_ID('dbo.TestTable', 'U') IS NOT NULL
DROP TABLE dbo.TestTable;
CREATE TABLE [dbo].[TestTable]
(
[value2] [char](1) NULL,
[value1] [char](1) NULL
) ON [PRIMARY]
GO
DECLARE #i int = 0
WHILE #i < 262
BEGIN
SET #i = #i + 1
INSERT INTO [dbo].[TestTable]([value2], [value1])
VALUES (null, null)
END
C# console (.net framework 4.7) code as below
class Program
{
// [change here]
static string sourceConn = #"Server={YourServer};Database={YourDatabase};User ID={userYourName};Password={yourPassword};connect timeout=15";
static void Main(string[] args)
{
CopyTable(sourceConn, sourceConn, "TestTable", "testTableBAK");
Console.ReadLine();
}
static void CopyTable(string sConnSource, string sConnDest, string sTableSource, string sTableDest)
{
if (IsTableExist(sConnDest, sTableDest))
{
RunNonQuerySQL(sConnDest, "DROP TABLE " + sTableDest);
Console.WriteLine($"existing table {sTableDest} dropped");
}
CopySchema(sConnDest, sTableSource, sTableDest);
using (SqlConnection connSource = new SqlConnection(sConnSource))
{
connSource.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connSource;
cmd.CommandText = "SELECT * FROM " + sTableSource;
// using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sConnDest, SqlBulkCopyOptions.KeepNulls | SqlBulkCopyOptions.KeepIdentity))
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sConnDest))
{
// sqlBulkCopy.BatchSize = 1380; // this optional setting will work if set value smaller than 1397 for testTable on my new server (SQL server 13.0.5102.14)
// sqlBulkCopy.BatchSize = 261; // this optional setting will work if set value smaller than 261 for testTable on 2 older server (SQL server 11.0.7001)
sqlBulkCopy.DestinationTableName = sTableDest;
SqlDataReader reader = cmd.ExecuteReader();
try
{
// exception here
sqlBulkCopy.WriteToServer(reader);
Console.WriteLine("table copied");
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
sqlBulkCopy.Close();
}
}
}
static bool IsTableExist(string sConn, string sTableName)
{
bool result = false;
using (SqlConnection conn = new SqlConnection(sConn))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
string[] s = sTableName.Split('.');
if (s.Length > 1)
{
cmd.CommandText = "select count (*) as counter from information_schema.tables where table_name = '" + s[1] + "' and TABLE_SCHEMA='" + s[0] + "'";
}
else
{
cmd.CommandText = "select count (*) as counter from information_schema.tables where table_name = '" + sTableName + "'";
}
cmd.Connection = conn;
var count = Convert.ToInt32(cmd.ExecuteScalar());
result = count > 0;
}
return result;
}
static bool RunNonQuerySQL(string sConn, string sSQL)
{
bool result = false;
using (SqlConnection conn = new SqlConnection(sConn))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = sSQL;
cmd.Connection = conn;
var count = cmd.ExecuteNonQuery();
result = true;
}
return result;
}
static public bool CopySchema(string sConn, string sTableSource, string sTableDest)
{
return RunQuerySQL(sConn, "select * into " + sTableDest + " from " + sTableSource + " where 1=2");
}
static public bool RunQuerySQL(string sConn, string sSQL)
{
using (SqlConnection conn = new SqlConnection(sConn))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = sSQL;
cmd.Connection = conn;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
return true;
}
else
{
return false;
}
}
}
}
I just experienced this error.
I tried to insert a string with a lenght of 5 into a table column with a definition of "varchar(4)".
The error message in my case was:
"Received an invalid column length from the bcp client for colid 2".
"Colid 2" refered to the second column of the row (DataRow) that was part of the DataTable which I used as parameter for the call to the SqlBulkCopy.WriteToServer(DataTable table) method.
The solution in my case was to add validation code that checks the lenght of the strings in my input data before trying to call SqlBulkCopy.WriteToServer().
They're must be a minor error somewhere in my code that im not seeing as to why on my web page , the gridview only outputs one row when i know the query works/
Both rows from management studio
Only one row in ASP page
heres my c#
string AdminID = Request.QueryString["ID"];
string AdminsCurrentLocation = Request.QueryString["Location"];
//retrieve admin location
try
{
string connectionString = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
//
// Create new SqlConnection object.
//
using (SqlConnection connection5 = new SqlConnection(connectionString))
{
connection5.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM [DB_A05369_WATERQ].[dbo].[S_CONTROL] WHERE LOGIN = '" + AdminID + "'", connection5))
{
//
// Invoke ExecuteReader method.
//
using (SqlDataReader reader2 = command.ExecuteReader())
{
reader2.Read();
TempLocationIdbox.Text = (reader2["ALL_LOCATION_ACCESS"].ToString());
}
}
connection5.Close();
}
}
catch (Exception ex) { }
if(TempLocationIdbox.Text == "Y")
{
string strSQLconnection = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand = new SqlCommand("SELECT DISTINCT ACT.ROW_ID , ACT.CREATED , MEM.FIRST_NAME , MEM.LAST_NAME , LOC.NAME , CAT.NAME , SER.NAME , EMP.FIRST_NAME , EMP.LAST_NAME , SER.DURATION , ACT.CASH , COS.NAME , ACT.COMMENTS FROM " +
"S_ACTIVITY ACT, S_LOCATION LOC, S_CATEGORY CAT, S_EMPLOYEE EMP, S_SERVICE SER, S_COST_CODE COS, S_MEMBER MEM " +
"WHERE ACT.EMPLOYEE_ID = EMP.ROW_ID AND ACT.SERVICE_ID = SER.ROW_ID AND ACT.CATEGORY_ID = CAT.ROW_ID AND ACT.COST_CODE_ID = COS.ROW_ID AND ACT.LOCATION_ID = LOC.ROW_ID AND ACT.MEMBER_ID = MEM.ROW_ID", sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
//collect rowID
string retrievedROWID = "";
if (reader.HasRows)
{
reader.Read();
string temp1 = reader["ROW_ID"].ToString();
retrievedROWID = temp1;
GridView1.DataSource = reader;
GridView1.DataBind();
}
sqlConnection.Close();
}
else if (TempLocationIdbox.Text == "N")
{
string strSQLconnection1 = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection1 = new SqlConnection(strSQLconnection1);
SqlCommand sqlCommand1 = new SqlCommand("SELECT * FROM S_LOCATION WHERE NAME = '" + AdminsCurrentLocation + "'", sqlConnection1);
sqlConnection1.Open();
string locationrowID = "";
SqlDataReader reader12 = sqlCommand1.ExecuteReader();
if (reader12.HasRows)
{
reader12.Read();
locationrowID = reader12["ROW_ID"].ToString();
}
sqlConnection1.Close();
string strSQLconnection = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand = new SqlCommand("SELECT DISTINCT ACT.ROW_ID , ACT.CREATED , MEM.FIRST_NAME , MEM.LAST_NAME , LOC.NAME , CAT.NAME , SER.NAME , EMP.FIRST_NAME , EMP.LAST_NAME , SER.DURATION , ACT.CASH , COS.NAME , ACT.COMMENTS FROM "+
"S_ACTIVITY ACT, S_LOCATION LOC, S_CATEGORY CAT, S_EMPLOYEE EMP, S_SERVICE SER, S_COST_CODE COS, S_MEMBER MEM "+
"WHERE ACT.EMPLOYEE_ID = EMP.ROW_ID AND ACT.SERVICE_ID = SER.ROW_ID AND ACT.CATEGORY_ID = CAT.ROW_ID AND ACT.COST_CODE_ID = COS.ROW_ID AND "+
"ACT.LOCATION_ID = '"+ locationrowID + "' AND ACT.MEMBER_ID = MEM.ROW_ID AND LOC.NAME = '"+ AdminsCurrentLocation + "'", sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
//collect rowID
string retrievedROWID = "";
if (reader.HasRows)
{
reader.Read();
string temp1 = reader["ROW_ID"].ToString();
retrievedROWID = temp1;
GridView1.DataSource = reader;
GridView1.DataBind();
}
sqlConnection.Close();
}
What stumps me is that my other query is working fine for the case where TempLocationIdbox.Text == "Y"...
Thanks , any help would be much appreciated.
Instead of using if (reader.HasRows) you need to use while (reader.Read()).Also created some kind of collection for example List<T> and populate it with results inside the while loop.Then outside the loop set the DataSource of the GridView control to point to List<T>.Here's a complete example:
public class Activity
{
public int RowID { get; set; }
public DateTime Created { get; set; }
public string FirstName { get; set; }
}
public partial class UsingSqlDataReader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
this.GetData();
}
}
private void GetData()
{
string cs = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
var activities = new List<Activity>();
using (var con = new SqlConnection(cs))
{
using(var cmd = new SqlCommand("SELECT ACT.ROW_ID,ACT.CREATED,ACT.FIRST_NAME FROM [dbo].[S_ACTIVITY] ACT", con))
{
cmd.CommandType = System.Data.CommandType.Text;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var activity = new Activity();
activity.RowID = Convert.ToInt32(reader["ROW_ID"]);
activity.Created = DateTime.Parse(reader["CREATED"].ToString());
activity.FirstName = Convert.ToString(reader["FIRST_NAME"]);
activities.Add(activity);
}
}
}
}
GridView1.DataSource = activities;
GridView1.DataBind();
}
}
Output:
A better solution would be to put your in-line query in a stored proc and execute the stored proc.
You could also bring it in a dataset and bind the gridview with that. but that is completely your choice.
In-line queries are very error prone and results could be unpredictable hence refrain using that.
I am trying to display pictures from my SQLSEVER database on my website. My users have a picture field with a picture datatype. If the picture column is null, then I want the picture displayed to be a egg.jpg, but right now for every person their picture is egg.jpg, even if they have a picture in the database. Here is my method.
public string getImageUrl()
{
System.Data.SqlClient.SqlConnection sc = new System.Data.SqlClient.SqlConnection();
sc.ConnectionString = "Server =MRCOMPUTER2\\SQLEXPRESS; Database = WBL;Trusted_Connection=Yes;";
sc.Open();
System.Data.SqlClient.SqlCommand insert = new System.Data.SqlClient.SqlCommand();
insert.Connection = sc;
insert.CommandText = "SELECT profilePicture from SystemUser";
insert.ExecuteNonQuery();
SqlDataReader reader = insert.ExecuteReader();
string url = "";
while (reader.Read())
{
if ( !DBNull.Value.Equals(reader[0]))
{
url = "data:Image / png; base64," + Convert.ToBase64String((byte[])reader[0]);
}
else {
url = "images/egg.jpg";
}
}
return url;
}
Your code returns the image for the last user in your table.
Here:
insert.CommandText = "SELECT profilePicture from SystemUser";
you select all users from the table (not just the one you currently show). Then:
while (reader.Read())
{
...
url = ...
...
}
you re-assign url inside every iteration of your while loop. This is semantically equivalent to:
url = ... /* The value determined from the last record of the reader. */
Thus, all your users show the same image - the one of the last user in your table.
You SELECT statement is attached into a ExecuteNonQuery?
Take it off.
Just perform the READER statement...
Try this:
static void Main(string[] args)
{
string connectionString = "Server=.;Database=AA;Trusted_Connection=True;";
/*
CREATE TABLE [dbo].[SystemUser]
(
[ProfilePicture] [varbinary](max) NULL
)
*/
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = #"
INSERT [AA].[dbo].[SystemUser] ([ProfilePicture]) VALUES (#ProfilePicture);
INSERT [AA].[dbo].[SystemUser] ([ProfilePicture]) VALUES (NULL);
";
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = sql;
command.CommandType = CommandType.Text;
byte[] bytes = File.ReadAllBytes(#"1.jpg");
command.Parameters.AddWithValue("#ProfilePicture", bytes);
connection.Open();
command.ExecuteNonQuery();
}
DataSet ds = new DataSet();
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = #"
SELECT TOP 1000 [ProfilePicture] FROM [AA].[dbo].[SystemUser];
";
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = sql;
command.CommandType = CommandType.Text;
connection.Open();
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(ds);
}
var rows = ds.Tables[0].Rows.Cast<DataRow>();
foreach (DataRow row in rows)
{
byte[] bytes = row.Field<byte[]>(0);
if (bytes != null)
{
string fileName = Guid.NewGuid().ToString("N") + ".jpg";
File.WriteAllBytes(fileName, bytes);
}
}
}
Can you try using the name of the column such as
var Val = (String)reader["column name"];
Also, try something like this to test:
while (reader.Read())
{
var testVal = reader.GetString(0);
Var testVal2 = reader.GetString(1);
i have a project, and part of it asks the user to input the ID of the patient to show his/her details
This is my code
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=hospital database.accdb";
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
sql = "SELECT * FROM Patients";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
dbReader = dbCmd.ExecuteReader();
listBox1.Items.Clear();
if (dbReader.HasRows)
{
while (dbReader.Read())
{
if (dbReader["PatientID"] != DBNull.Value)
{
int anInteger;
anInteger = Convert.ToInt32(textBox7.Text);
anInteger = int.Parse(textBox7.Text);
if (anInteger == 101)
{
}
}
}
}
in the IF statement, i dont know what to write in it, to display on the row of the patient with this ID only
Please Help!!
Instead of selecting all rows, it is much more efficient to filter the one row you are looking for using a parameter and modifying your SQL statement as follows.
sql = "SELECT * FROM Patients WHERE PatientID = [pID]";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
dbcmd.Parameters.AddWithValue("pID", 101);
dbReader = dbCmd.ExecuteReader();
I would also suggest looking into the "using" clause. Here's a SO example.
sql = "SELECT Count(*) FROM Patients WHERE PatientID = #PID";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
dbcmd.Parameters.AddWithValue("#PID", 101);
Int32 Cnt = dbCmd.ExecuteScalar();
if ( Cnt > 0)
{
// Do Something
}
else { // Do something}
you have to use a variable to be sure that your ID was found and and break; to exit your loop once it was found
if (dbReader.HasRows)
{
bool found = false;
while (dbReader.Read())
{
if (dbReader["PatientID"] != DBNull.Value)
{
int anInteger;
anInteger = Convert.ToInt32(textBox7.Text);
anInteger = int.Parse(textBox7.Text);
if (anInteger == 101)
{
found = true ; Break;
}
}
}
}
int anInteger = Convert.ToInt32(textBox7.Text);
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=hospital database.accdb";
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
sql = "SELECT * FROM Patients where PatientID=#PatientID";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Parameters.AddWithValue("#PatientID",anInteger);
dbCmd.Connection = dbConn;
dbReader = dbCmd.ExecuteReader();
listBox1.Items.Clear();
while (dbReader.Read())
{
//now display the reader values here : sample
//TextBox1.Text=dbReader["name"].ToString();
}
I ran the SQL Query in SQL Server Management Studio and it worked.
I get the following error in my WinForm C# application
The parameterized query '(#word1 text)SELECT distinct [database].[dbo].[tableName].[n' expects the parameter '#word1', which was not supplied.
Here is my code
private void buttonRunQuery_Click(object sender, EventArgs e)
{
if (connection == null)
{
connection = ConnectionStateToSQLServer();
SqlCommand command = new SqlCommand(null, connection);
command = createSQLQuery(command);
GetData(command);
}
else
{
SqlCommand command = new SqlCommand(null, connection);
command = createSQLQuery(command);
GetData(command);
}
}
private SqlCommand createSQLQuery(SqlCommand command)
{
string[] allTheseWords;
if (textBoxAllTheseWords.Text.Length > 0)
{
allTheseWords = textBoxAllTheseWords.Text.Split(' ');
string SQLQuery = "SELECT distinct [database].[dbo].[customerTable].[name], [database].[dbo].[customerTable].[dos], [database].[dbo].[customerTable].[accountID], [database].[dbo].[reportTable].[customerID], [database].[dbo].[reportTable].[accountID], [database].[dbo].[reportTable].[fullreport] FROM [database].[dbo].[reportTable], [database].[dbo].[customerTable] WHERE ";
int i = 1;
foreach (string word in allTheseWords)
{
var name = "#word" + (i++).ToString();
command.Parameters.Add(name, SqlDbType.Text);
//(name, SqlDbType.Text).Value = word;
SQLQuery = SQLQuery + String.Format(" [database].[dbo].[reportTable].[fullreport] LIKE {0} AND ", name);
}
SQLQuery = SQLQuery + " [database].[dbo].[customerTable].[accountID] = [database].[dbo].[reportTable].[accountID]";
command.CommandText = SQLQuery;
}
MessageBox.Show(command.CommandText.ToString());
return command;
}
public DataTable GetData(SqlCommand cmd)
{
//SqlConnection con = new SqlConnection(connString);
//SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
connection.Open();
DataTable dt = new DataTable();
da.Fill(dt);
connection.Close();
return dt;
}
The error is happening on da.Fill(dt)
Any suggestions would be helpful
Thank you
In your example, you have commented out the line where you set the value of the Parameter:
command.Parameters.Add(name, SqlDbType.Text);
//(name, SqlDbType.Text).Value = word;
If you do not set a value for a parameter, it is ignored (and won't exist).
Change to this:
command.Parameters.AddWithValue(name, word);
For clarity, consider this quote:
The value to be added. Use DBNull.Value instead of null, to indicate a null value.
From here: SqlParameterCollection.AddWithValue Method
On var name = "#word" + (i++).ToString(); use just i, increment somewhere else.