how to create a table having spaces between the words? - c#

I am trying to create a table using code.
Here is my code.
private void btnOK_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Open) { con.Close(); }
con.Open();
string s = "CREATE TABLE "+"" + rchtxtFieldCode.Text + " "+ " (" + rchFieldTitle.Text + " " + combDataType.Text + "" + ")";
SqlCommand cmd = new SqlCommand(s, con);
if (cmd.ExecuteNonQuery() >= 1)
{
MessageBox.Show("created");
}
con.Close();
}
It is creating the table if the table name has single word.. It is showing exception if there is space between the words(eg: Sales Info)

If this is for SQL Server you use square brackets:
string s = "CREATE TABLE ["+"" + rchtxtFieldCode.Text + "] "+ " ([" + rchFieldTitle.Text + "] " + combDataType.Text + "" + ")";
In fact you should always use square brackets to stop these kind of errors happening.
Also ensure you are sanitising your strings otherwise you might have SQL injection issues.

Just add Box braces:
string s = "CREATE TABLE ["+"" + rchtxtFieldCode.Text + "] "+ " (" + rchFieldTitle.Text + " " + combDataType.Text + "" + ")";
//^_______________________________^

Do not use spaces in table or field names.In this, Try to change query with Square brackets i.e.
For example ,
sqlString = "CREATE TABLE [All Students]"

use this code, i think it will give you the desire output.
private void btnOK_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Open) { con.Close(); }
con.Open();
string s = "CREATE TABLE '"+rchtxtFieldCode.Text + "'(" +"'"+rchFieldTitle.Text +"'" + combDataType.Text + "" + ")";
SqlCommand cmd = new SqlCommand(s, con);
if (cmd.ExecuteNonQuery() >= 1)
{
MessageBox.Show("created");
}
con.Close();
}

Related

Error in C# insert statement for SQL Server

I am trying to pass an insert statement in a C# Winforms to SQL Server. I keep getting a syntax error that just doesn't make sense to me
error in syntax near "("
My syntax is perfectly fine, as when I copy and paste into SQL Server Mgmt Studio, the code runs perfectly.
Any help would be greatly appreciated!
Thanks!
try
{
using (var cmd = new SqlCommand("INSERT INTO " + intodrop.SelectedText + "(" + colnamedrop.SelectedText.ToString() + "," +
colnamedrop2.SelectedText.ToString() + ") " + "VALUES" + " (" + valuebox.Text + ");"))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#tbl", intodrop.SelectedText);
cmd.Parameters.AddWithValue("#colname", colnamedrop.SelectedText);
cmd.Parameters.AddWithValue("#values", valuebox.Text);
cmd.Parameters.AddWithValue("#colname2", colnamedrop2.SelectedText);
con.Open();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception g)
{
MessageBox.Show("Error during insert: " + g.Message);
}
Check if SelectedText property returns right values. Try to use Text property instead.
var cmd = new SqlCommand("INSERT INTO " + intodrop.Text +
"(" + colnamedrop.Text + ',' + colnamedrop2.Text + ") "
+ "VALUES" + " (" + valuebox.Text + ");")
You missed comma between column names when insert sql statement preparing. When printing you have comma and display correctly.
Concatenated sql statement without any inputs validation is widely open for sql injection attacks. Try to use parameter as much as possible.
It looks like you are trying to insert values to two columns, but you are appending them like this "Col1+Col2", instead of "Col1+','+Col2".
using (var cmd = new SqlCommand("INSERT INTO " + intodrop.SelectedText + "(" + colnamedrop.SelectedText.ToString() + ','+
colnamedrop2.SelectedText.ToString() + ") " + "VALUES" + " (" + valuebox.Text + ");"))
I hope this resolves the issue.
First try hard coding your insert value after that change it based on your need. Confirm the column data types are assigned correctly.
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Property ( FolioNo,PropertyType) VALUES (001,'WIP')"))
{
cmd.Connection = con;
con.Open();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception g)
{
MessageBox.Show("Error during insert: " + g.Message);
}
1) You should have two texbox for entering your values. If no column names you gray the value of column 1, ditto for column 2.
This allows you not to have to enter quote (do not forget to make an escape quotes
2) use the string.format function for more readability
try
{
//Add columns selected
List<string> Mycolumns = new List<string>();
If (! string.IsNullOrEmpty(colnamedrop.Text)) Mycolumns.Add(colnamedrop.Text);
If (! string.IsNullOrEmpty(colnamedrop2.Text)) Mycolumns.Add(colnamedrop2.Text);
//Add values selected with escaped quoted and string quoted
List<string> Myvalues ​​= new List<string>();
If (! string.IsNullOrEmpty(colvalue1.Text)) Myvalues.Add("'" + colvalue1.Text.Replace("'", "''") + "'");
If (! string.IsNullOrEmpty(colvalue2.Text)) Myvalues.Add("'" + colvalue2.Text.Replace("'", "''") + "'");
//If nothing selected, no action
if (Mycolumns.Count==0 && Myvalues.Count==0) return;
//Build query
String Query = string.Format ( "INSERT INTO {0} ({1}) VALUES ({2})", intodrop.Text, string.Join(Mycolumns, ", "), string.Join(Myvalues, ", "));
//Execute query
using (var cmd = new SqlCommand(Query, con ))
{
con.Open();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
con.Close();
}
}
catch (Exception g)
{
MessageBox.Show("Error during insert: " + g.Message);
}

sql missing comma

protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
string loginID = (String)Session["UserID"];
string ID = txtID.Text;
string password = txtPassword.Text;
string name = txtName.Text;
string position = txtPosition.Text;
int status = 1;
string createOn = validate.GetTimestamp(DateTime.Now); ;
string accessRight;
if (RadioButton1.Checked)
accessRight = "Administrator";
else
accessRight = "Non-administrator";
if (txtID.Text != "")
ClientScript.RegisterStartupScript(this.GetType(), "yourMessage", "alert('" + ID + "ha " + password + "ha " + status + "ha " + accessRight + "ha " + position + "ha " + name + "ha " + createOn + "');", true);
string sqlcommand = "INSERT INTO USERMASTER (USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES ("+ ID + "," + password + "," + name + "," + position + "," + accessRight + "," + status + "," + createOn + "," +loginID+ ")";
readdata.updateData(sqlcommand);
}
I am passing the sqlcommand to readdata class for execute..and its throw me this error..
ORA-00917: missing comma
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: ORA-00917:
missing comma.
The readdata class function code as below.
public void updateData(string SqlCommand)
{
string strConString = ConfigurationManager.ConnectionStrings["SOConnectionString"].ConnectionString;
OleDbConnection conn = new OleDbConnection(strConString);
OleDbCommand cmd = new OleDbCommand(SqlCommand, conn);
OleDbDataAdapter daPerson = new OleDbDataAdapter(cmd);
conn.Open();
cmd.ExecuteNonQuery();
}
Given that most of your columns are variable-length character, they must be enclosed in single quotes.
So, instead of:
string sqlcommand = "INSERT INTO myTable (ColumnName) VALUES (" + InputValue + ")";
You would, at minimum, need this:
string sqlcommand = "INSERT INTO myTable (ColumnName) VALUES ('" + InputValue + "')";
The result of the first statement, for an InputValue of "foo", would be:
INSERT INTO myTable (ColumnName) VALUES (foo)
which would result in a syntax error.
The second statement would be formatted correctly, as:
INSERT INTO myTable (ColumnName) VALUES ('foo')
Additionally, this code seems to be using values entered directly by the user, into txtID, txtPassword, and so on. This is a SQL Injection attack vector. Your input needs to be escaped. Ideally, you should use parameterized queries here.
This appears to be c#. Please update your tags accordingly.
At any rate, if it is .Net, here is some more information about parameterizing your queries:
OleDbCommand.Parameters Property
OleDbParameter Class
Try this
string sqlcommand = "INSERT INTO USERMASTER (USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES ('"+ ID + "','" + password + "','" + name + "','" + position + "','" + accessRight + "','" + status + "','" + createOn + "','" +loginID+ "')";
Concatenating the query and executing it is not reccomended as it may cause strong SQl Injection. Suppose if any one of those parameters contain a comma(,) like USERPWD=passwo',rd then query will devide it as passwo and rd by the comma. This may be a problem
It is recommended that you use "Parameterized queries to prevent SQL Injection Attacks in SQL Server" and hope it will resolve your issue.
Your code can be rewritten as follows
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
string loginID = (String)Session["UserID"];
string ID = txtID.Text;
string password = txtPassword.Text;
string name = txtName.Text;
string position = txtPosition.Text;
int status = 1;
string createOn = validate.GetTimestamp(DateTime.Now); ;
string accessRight;
if (RadioButton1.Checked)
accessRight = "Administrator";
else
accessRight = "Non-administrator";
if (txtID.Text != "")
ClientScript.RegisterStartupScript(this.GetType(), "yourMessage", "alert('" + ID + "ha " + password + "ha " + status + "ha " + accessRight + "ha " + position + "ha " + name + "ha " + createOn + "');", true);
string strQuery;
OleDbCommand cmd;
strQuery = "INSERT INTO USERMASTER(USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES(#ID,#password,#name,#position,#accessRight,#status,#createOn,#loginID)";
cmd = new OleDbCommand(strQuery);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#password", password);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#position", position);
cmd.Parameters.AddWithValue("#accessRight", accessRight);
cmd.Parameters.AddWithValue("#status", status);
cmd.Parameters.AddWithValue("#createOn", createOn);
cmd.Parameters.AddWithValue("#loginID", loginID);
bool isInserted = readdata.updateData(cmd);
}
rewrite your updateData data as follows
private Boolean updateData(OleDbCommand cmd)
{
string strConString = ConfigurationManager.ConnectionStrings["SOConnectionString"].ConnectionString;
OleDbConnection conn = new OleDbConnection(strConString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}

How to create table by giving width option?

I am trying to create table.
Below is my code:
private void btnOK_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Open) { con.Close(); }
con.Open();
string s = "CREATE TABLE ["+"" + rchtxtFieldCode.Text + "] "+ " (" + rchFieldTitle.Text + " " + combDataType.Text + "("+txtWidth.Text+")" + ")";
SqlCommand cmd = new SqlCommand(s, con);
if (cmd.ExecuteNonQuery() >= 1)
{
MessageBox.Show("created");
}
con.Close();
}
It is creating table. But, it is showing exception when the datatype is int or text.
I want every datatype to function properly.
Try this
string width = string.IsNullOrEmpty(txtWidth.Text.Trim()) ? string.Empty : "(" + txtWidth.Text.Trim() + ")"
string s = "CREATE TABLE [" + "" + rchtxtFieldCode.Text + "] " + " (" + rchFieldTitle.Text + " " + combDataType.Text + width + ")";

Unable to connect to any of the specified MySQL hosts

Here is the problem. I am trying to execute a query and its throwing and exception at connection.Open. Strangely, on the same application I am executing a "Select" query and it works fine. But when I execute the "Update" query it throws this Unable to connect to any of the specified MySQL hosts error. Been stuck on this forever. Can someone spot where I am going wrong.
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
timerEnabled = 1;
}
connection.Open();
//update the settings to the database table
MySqlCommand command = connection.CreateCommand();
command.CommandText = "update Admin_Settings set Difficulty='" + comboBox3.Text + "'," + "NoOfQuestions='" + comboBox4.Text + "'," + "NoOfChoices='" + comboBox5.Text + "'," +
"Subject='" + comboBox8.Text + "'," + "Timer='" + comboBox2.Text + "," + "TimerEnabled=" + timerEnabled + "," + "TimerType='" + comboBox1.Text + "'";
command.ExecuteNonQuery();
MessageBox.Show("Settings updated");
}
I'm going to recommend you do the following:
private void button1_Click(object sender, EventArgs e)
{
using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connString))
{
if (radioButton1.Checked)
{
timerEnabled = 1;
}
connection.Open();
//update the settings to the database table
MySqlCommand command = connection.CreateCommand();
command.CommandText = "update Admin_Settings set Difficulty='" + comboBox3.Text + "'," + "NoOfQuestions='" + comboBox4.Text + "'," + "NoOfChoices='" + comboBox5.Text + "'," +
"Subject='" + comboBox8.Text + "'," + "Timer='" + comboBox2.Text + "," + "TimerEnabled=" + timerEnabled + "," + "TimerType='" + comboBox1.Text + "'";
command.ExecuteNonQuery();
MessageBox.Show("Settings updated");
}
}
I understand that you are thinking to yourself, that you should maintain your connection for ease of use and blah blah, but in my experience, it's wasted effort. What ends up happening its lots of trouble that you don't want or need. You end up not realizing that you have a connection open somewhere else and you spend hours troubleshooting things that you shouldn't. Open your connection, close it when you are done.
If you want to have a single connection object, that's fine, but use the using pattern so that it is disposed of every time, and always start fresh with your connections.
NOTE: replace my connection with yoru MySqlConnection object!
As Mike said, you always better use "using" block as it disposes any connection once it goes out of using block. I used two using blocks below one for connection and other for command object.
Try this
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(connString))
{
if (radioButton1.Checked)
{
timerEnabled = 1;
}
string queryString = "update Admin_Settings set Difficulty='" +
comboBox3.Text + "'," + "NoOfQuestions='" + comboBox4.Text + "'," +
"NoOfChoices='" + comboBox5.Text + "'," + "Subject='" + comboBox8.Text +
"'," + "Timer='" + comboBox2.Text + "," + "TimerEnabled=" + timerEnabled +
"," + "TimerType='" + comboBox1.Text + "'";
using (SqlCommand command = new SqlCommand(queryString, connection))
{
//update the settings to the database table
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
MessageBox.Show("Settings updated");
}
}
}

OverFlow Exception in OLEDB

I am getting an error while i am trying to insert a user id of my client in the ms access database.
The error i am getting is Overflow.
when i am trying to insert its getting the above error.
I am using these code.
OleDbCommand cmd = new OleDbCommand("insert into UserInfo " + "([firstname], [lastname], [gender], [occupation], [expirydate], [UserId], [phoneno]) " + " values('" + txt_FirstName.Text + "','" + txt_LastName.Text + "','" + cmb_Gender.Text + "','" + cmb_Occupation.Text + "','" + txt_expiryDate.Text + "','" + txt_HardDiskId.Text + "','" + txt_PhoneNo.Text + "');", con);
OleDbCommand cmd1 = new OleDbCommand("select * from UserInfo where (HardDiskId='" + txt_HardDiskId.Text + "')", con);
int temp = 0;
try
{
con.Open();
string count = (string)cmd1.ExecuteScalar();
if ((count == "") || (count == null))
{
temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
MessageBox.Show("User ID of " + txt_FirstName.Text + " " + txt_LastName.Text + " has been added");
}
else
{
MessageBox.Show("Record not added");
}
}
else
{
MessageBox.Show("User ID of " + txt_FirstName.Text + " already exists. Try another user ID.");
}
}
Aside from being open to SQL Injection (which you should parameterize your OleDbCommand), first thought on a problem is what you are trying to store the data. Do any of the text fields have special characters or apostrophe in name which would otherwise pre-terminate your embedded .... '" + nextField + "' ..." entries and throw the balance off.
Another... don't know if the parser is picky or not... but a space after values, before open paren.... " values(" to " values (".
Third, and more probable the issue is the expiration date. If its a date field, and you are trying to put in as text, it might be failing on the data type conversion.

Categories