I am trying to perform
ALTER TABLE
command in my app, but when running, I am getting this error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'VARCHAR(10) NOT NULL' at line 1
Here is my code:
for (int k = 0; k < dlzkaTab; k++)
{
string query1 = "ALTER TABLE reflextime ADD " + atributes[k] + " VARCHAR(10) NOT NULL";
MySqlCommand cmd = new MySqlCommand(query1, conect);
cmd.ExecuteScalar();
}
Can anyone please help me?
EDIT:
Here is full code. In the firs for loop I am reading first row from xls file and I am putting it into array atributes. As you can see, I was trying to print out every loaded cell. It worked well (It was printing correct values). However after this for loop the array is printing nothing (empty messagebox).
for (int j = 2; j < colCount; j++)
{
string atr = xlRange.Cells[1, j].Text;
atributes[j]=atr;
MessageBox.Show(atributes[j]);
}
MessageBox.Show("Súbor načítaný");
int dlzkaTab = atributes.Length;
MessageBox.Show(atributes[1]); //empty messagebox
for (int k = 0; k < dlzkaTab; k++)
{
string query1 = "ALTER TABLE reflextime ADD COLUMN " + atributes[k] + " VARCHAR(10) NOT NULL";
MySqlCommand cmd = new MySqlCommand(query1, conect);
cmd.ExecuteScalar();
}
I think you are trying to add a column to the table.
You missed COLUMN keyword in the statement before column name that is being added.
"ALTER TABLE reflextime ADD COLUMN " + atributes[k] + " VARCHAR(10) NOT NULL"
You need to use ExecuteNonQuery instead of ExecuteScalar
And also check your each atributes[k] fro value exist or not
Try this
for (int k = 0; k < dlzkaTab; k++)
{
string query1 = "ALTER TABLE reflextime ADD " + atributes[k] + " VARCHAR(10) NOT NULL";
MySqlCommand cmd = new MySqlCommand(query1, conect);
cmd.ExecuteNonQuery();
}
Related
I know this question have been asked several times, but none of answers has helped me resolving this issue.
So, i'm writing data transfer utility, copying data from one table of OleDb database to table of another OleDb database.
I have read all the data from the source database, and i'm trying to write, but always gets this error
Must declare the scalar variable "#CategoryID"
Here's the code
// generating the insert string below
string insert = "INSERT INTO Categories VALUES (";
for(int i = 0; i < cols.Length; i++)
{
string coma = ", ";
if (i == cols.Length - 1)
coma = " )";
insert += "#" + cols[i] + coma;
}
try
{
while (src_reader.Read()) // reading from source database
{
dstcmd.CommandText = insert;
for (int i = 0; i < cols.Length; i++)
{
string temp = "#" + cols[i]; // cols is array of column names
dstcmd.Parameters.AddWithValue(temp, src_reader[cols[i]]);
// for debug purposes... below is screenshot of error
Console.Write(temp + " " + src_reader[cols[i]] + "\n");
}
Console.WriteLine("");
// point of error
dstcmd.ExecuteNonQuery();
}
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
Here's the screenshot of error.
CategoryID is the first column of the table and hence the first value that is being inserted.
Any help will be appreciated. If i missed any information or something does not make sense, please do let me know.
Try changing this part:
// generating the insert string below
string insert = "INSERT INTO Categories VALUES (";
for(int i = 0; i < cols.Length; i++)
{
string coma = ", ";
if (i == cols.Length - 1)
coma = " )";
insert += "#" + cols[i] + coma;
}
to
// generating the insert string below
string insert = "INSERT INTO Categories VALUES (";
for(int i = 0; i < cols.Length; i++)
{
string coma = ", ";
if (i == cols.Length - 1)
coma = " )";
insert += "?" + coma;
}
You don't need to use parameter names in VALUES, but just ? placeholders. However, make sure the order of parameters when you add them matches the order of columns in the table.
Also, it may be better to explicitly specify the column list in the INSERT clause, like:
string insert = "INSERT INTO Categories (Col1, Col2, Col3, etc.) VALUES (";
See if you want to make that column names list dynamically generated too. But I suggest to get it working for the static column list first and then convert it to dynamic version.
Also, if you don't specify the column name list for INSERT you will have specify values for all columns.
I am trying to update a column in the database, from a list
command = new SqlCommand("update Login_Users set Password=#a where UserName !='" + null + "'", Db);
Db.Open();
for (int i = 0; i < list.Count; i++)
{
list[i] = Encrypt(list[i]);
command.Parameters.AddWithValue("#a",list[i]);
int a = command.ExecuteNonQuery();
}
but I get this error:
variable name already been declared
Your command only has one parameter, but you are attempting to add a new one through each loop (via AddWithValue ... add with value).
Either put the command declaration in the loop (as below), or use one of the other methods to update the value.
Db.Open();
for (int i = 0; i < list.Count; i++)
{
command = new SqlCommand("update Login_Users set Password=#a where UserName !='" + null + "'", Db);
list[i] = Encrypt(list[i]);
command.Parameters.AddWithValue("#a",list[i]);
int a = command.ExecuteNonQuery();
}
In query you have one parameter called #a - check if your list has only one item. If not that's problem. Meybe it will be better to remove for loop and assign all parameters manually.
Why in query you do something like this:
where UserName !='" + null + "'"
I think much more readable is like this:
where UserName !=''
or
where UserName <>''
You have setup your SqlCommand with a SQL statement that includes a parameter #a. With that set, you can call the command multiple times via the ExecuteQuery after setting the parameter #a to different values.
Within your for loop, the statement command.Parameters.AddWithValue() is potentially adding to the command additional parameter, but no two parameters can have the same value so if your loop is executed more than once, you'll get the error you received.
Your SQL statement appears to be setting the password of all records in Login_Users to some encrypted value multiple times based on your list. If I understand correctly, maybe this would do what you want:
var command = new SqlCommand("update Login_Users set Password=#a where UserName !='" + null + "'", Db);
Db.Open();
command.Parameters.Add(new SqlParameter("#a",null));
for (int i = 0; i < list.Count; i++)
{
cmd.Parameters["#a"].Value = Encrypt(list[i]);
int a = command.ExecuteNonQuery();
}
Good luck!
this is what i am trying to do after receiving string from the serial port. i get whitespace between the data so i put two loops to eliminate them. i want to recieve data spanning multiple columns and a single row for every single run of do while loop.. Thanks in Advance
string text = sp.readline();
for (int i = 0; i < text.Length; )
{
p = text[i].ToString();
if (p != " ")
{
do
{
x += text[i].ToString();
s = text[i].ToString();
i++;
} while (s != " ");
try
{
string col = "column" + no.ToString();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO testdata("+col+")VALUES(?data)";
cmd.Parameters.Add("?data", MySqlDbType.VarChar).Value = x;
cmd.ExecuteNonQuery();
x = "";
p = "";
no++;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
} i++;
}
Sorry to say, you cannot, in any dialect of SQL, provide a table or column name as a bindable variable (or parameter). If it's working for MySQL that's terrific, but if you change over to any other DBMS make and model, it will suddenly stop working.
Also, INSERT means create a new row. You'll either need to insert all the column values at once in a single INSERT statement, or figure out how to INSERT one row and then UPDATE it for each new column value.
if you want to insert a single row having multiple column, then for loop is not required
following is for three columns
int no = 2;
cmd.CommandText = "INSERT INTO testdata(?col1,?col2,?col3)VALUES(?data1,?data2,?data3)";
cmd.Parameters.Add("?col1", MySqlDbType.String).Value = col1;
cmd.Parameters.Add("?col2", MySqlDbType.String).Value = col2;
cmd.Parameters.Add("?col3", MySqlDbType.String).Value = col3;
cmd.Parameters.Add("?data1", MySqlDbType.VarChar).Value = x1;
cmd.Parameters.Add("?data2", MySqlDbType.VarChar).Value = x2;
cmd.Parameters.Add("?data3", MySqlDbType.VarChar).Value = x3;
cmd.ExecuteNonQuery();
guys i have an SQL statement returning more than 1 value.
I am trying to use the StreamReader to get the values into an array as below
string sql = "select distinct COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME=' " + table + "' and CONSTRAINT_NAME like 'PK_%'";
SqlConnection conn2 = new SqlConnection(cnstr.connectionString(cmbDatabase.Text));
SqlCommand cmd_server2 = new SqlCommand(sql);
cmd_server2.CommandType = CommandType.Text;
cmd_server2.Connection = conn2;
conn2.Open();
//reader_sql = new StreamReader();
SqlDataReader reader_sql = null;
string[] colName = new string[200];
reader_sql = cmd_server2.ExecuteReader();
while (reader_sql.Read());
for (int rr = 0; rr < 20; rr++)
{
colName[rr] = reader_sql["COLUMN_NAME"].ToString();
}
It is not working, what am I doing wrong guys ?
You've got a stray ; turning your while into a tight loop, so instead try:
while (reader_sql.Read())
for (int rr = 0; rr < 20; rr++)
{
colName[rr] = reader_sql["COLUMN_NAME"].ToString();
}
You get the exception because
while (reader_sql.Read());
should be
while (reader_sql.Read())
{
for (int rr = 0; rr < 20; rr++)
{
colName[rr] = reader_sql["COLUMN_NAME"].ToString();
}
}
Perhaps you should remove the semicolon at the end of Read
while (reader_sql.Read())
{
for (int rr = 0; rr < 20; rr++)
colName[rr] = reader_sql["COLUMN_NAME"].ToString();
}
However, if your intention is to retrieve the columns belonging to the primary key, your code is wrong because you add 20 times the same primary key column, then repeat the same for the remaining columns ending with an array of 20 strings all equals to the last column in the primary key set. I think you should change your code to use a List(Of String) instead of a fixed length array and let the reader loop correctly on the primary key columns retrieved
List<string> pks = new List<string>();
while (reader_sql.Read())
{
pks.Add(reader_sql["COLUMN_NAME"].ToString());
}
EDIT: I have just noticed that your query contains a space before the table name. The string concatenation then produces an invalid table name, the query is syntactically right but doesn't return any data
string sql = "select distinct COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE " +
"where TABLE_NAME='" + table + "' and CONSTRAINT_NAME like 'PK_%'";
^ space removed here
And while you are at it, remove the string concatenation and use a parameterized query.....
string sql = "select distinct COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE " +
"where TABLE_NAME=#tName and CONSTRAINT_NAME like 'PK_%'";
SqlCommand cmd_server2 = new SqlCommand(sql, connection);
connection.Open();
cmd_server2.Parameters.AddWithValue("#tName", table);
I'm inserting a unique ID[KEY] in a dictionary with its corresponding time[VALUE].
I have only unique values in the ID column but i get the below error
"An item with the same key has already been added"
for (int j = 0; j < pro1.Count; j++)
{
string startend = "Select Id, CStart, CEnd from MBA1 where Channel='" + mbaChannel[allchan] + "' and Product='" + pro[allpro] + "' and ProgDate='" + pro1[j] + "'";
SqlCommand dat = new SqlCommand(startend, conn);
SqlDataReader datrdr = dat.ExecuteReader();
while (datrdr.Read())
{
start.Add(datrdr["Id"].ToString(), datrdr.GetDateTime(1));
end.Add(datrdr["Id"].ToString(), datrdr.GetDateTime(2));
}
datrdr.Close();
I'm sure there is no duplicate in my ID column. Please help!
Your query and dictionary update are in a loop. If there are no duplicate values in the Id column, then your query is returning at least 1 row in two different queries (different values of j in your example).
You are running your query pro1.Count times. If pro1.Count > 1, you will try to put duplicate items in your dictionary.