I want to create a table name in SQLite based on the user inputted textbox value or a declared string value. For example:
cmd.CommandText = #"CREATE TABLE '"+Machine_Name.Text+"' AS (Date, Cal_Date) VALUES (#Date, #CalDate)";
I'm receiving a newline in constant error right before the AS. I know this may be bad database design but it would be helpful for me to do it this way.
Your query syntax seems to be mixed up.
If you want to create table, you have to provide the column spec (names and datatypes), or if you use create table as, a valid select query has to be used to define the column names/types.
The last part of your statement with the values clause is a valid form for an INSERT, but not for a create table.
See the Documentation here for details.
The syntax to create a table is the following
cmd.CommandText = #"CREATE TABLE '" + newTable + "'" +
"(DATE DATETIME, CAL_DATE VARCHAR(256))";
This of course assumes that your fields are a DateTime and a VarChar.
In other words, after the tablename you put, between parenthesys, the name of the columns and their datatype.
I suggest also to pay particular attention to the value your user types for the name of the new table. This liberty to type anything could be very dangerous and it is the basic building block when a malicious user tries to create an Sql Injection attack.
string ct = "Create table '" + Textbox1.Text +"'(Column1, Column2)";
SQLiteCommand createCommand1 = new SQLiteCommand(ct, sqliteCon);
createCommand1.ExecuteNonQuery();
sqliteCon.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Related
I am trying to create a database and table in mySQL using C#. So far I can create a Schema in mysql through c#, but having trouble with creating table in that created schema.
User will enter the name of the schema to be created and then will enter the table name which will be created under the schema name entered before. Schema name and table names are taken in textbox values.
I am getting an error in table query the error is about syntax.
myQuery1.AppendFormat("CREATE SCHEMA {0}", databasenametxt.Text);
myQuery2.AppendFormat("CREATE TABLE {0} (name VARCHAR(20)) WHERE
database={0}",tblenametxt.Text,databasenametxt.Text);
string s1 = myQuery1.ToString();
string s2 = myQuery2.ToString();
MySqlCommand cmd = new MySqlCommand(s1, coat);
MySqlCommand cmd1 = new MySqlCommand(s2, coat);
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
myQuery1 is executed successfully and a schema is created with the name entered in databasenametxt.Text but in myquery2 I am getting error.
The way I understand it is that you want to dynamically create a schema and tables in it. I am not sure of the error you get, but try using the following query:
CREATE TABLE schema_name.table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... )
For replacing the schema_name and table_name, it should work like following:
myQuery2.AppendFormat("CREATE TABLE {schema_name}.{table_name} ( {column_name1} {data_type}, .... ), your_schema_name, your_table_name, column_name1, data_type1);
You can also just add strings:
myQuery2.AppendFormat("CREATE TABLE " + your_schema_name + "." + your_table_name + " ( " + column_name1 + " " + data_type1 + ")");
It is just that you are creating a query string, which would run on sql server.
Also, you can get all the msql syntax for creating a table at https://dev.mysql.com/doc/refman/8.0/en/create-table.html
Let me know if it helps!
As pointed out in comment the 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 'WHERE database=databasename' at line 1'"
is because "where database = .." is not valid syntax.
As schema is just a synonym for database in mysql you want
create database {0}
use {0}
create table {0} (`name` VARCHAR(20))
in each of your strings. Why the change to name? its a reserved word.
I need some correction with my query in C# & SQL Server.
I have a table called LoggedIn with name, password and clockin columns. I want it to insert into the table where name and password is from another table AND the clockin is the current time now.
string belepve = "INSERT INTO LoggedIn VALUES (SELECT name, password FROM Login WHERE password =" + Kod.login1 +" ,#MyDate";
SqlCommand command4 = new SqlCommand(belepve, con);
command4.Parameters.AddWithValue("#MyDate", DateTime.Now);
And then I just Execute the query.
There are multiple issues here.
First is the second parameter should also go as SqlParameter.
Second you have missing parenthesis at end.
Third you would need to specify the column names in which values should go in LoggedIn table.
Your working code would be something like:
string belepve = #"INSERT INTO LoggedIn (name,password,LoginDate)
VALUES (SELECT name,password,#MyDate
FROM Login
WHERE password =#Password
)";
SqlCommand command4 = new SqlCommand(belepve, con);
command4.Parameters.AddWithValue("#MyDate", DateTime.Now);
command4.Parameters.AddWithValue("#Password", Kod.login1);
Assuming that you have columns in LoggedIn table as named name,password and LoginDate, you might need to adjust the column names which you have actually in your table.
If you have same number of columns which you are already selecting then you can do it more simple like following:
SELECT name,password,#MyDate
INTO LoggedIn
FROM Login
WHERE password =#Password
But you need to be careful in the order of columns selecting otherwise value might go in different column than in what is expected.
Hope it helps.
I have a problem in button1 click event of inserting data into a table which table name be determined by whatever text is in textbox1
Should mean something like that:
tablename = textbox1.text;
sql = "INSERT INTO tablename ([itemserial], [itemname], [itemcount],[itemimage]) VALUES (#itemserial, #itemname, #itemcount, #itemimage)";
Having a textbox containing the name of your table is challenging because you should add extra care in handling this value. You should implement some kind of checking on this textbox value. A possible solution is to check against your database schema if the table typed by your user really exists.
You don't tell us which database system are you using so I will show an example using Sql Server
string tableName = textbox1.text;
using(SqlConnection cnn = new SqlConnection(... connectionstring...))
{
cnn.Open();
DataTable dt = cnn.GetSchema("TABLES");
DataRow[] rows = dt.Select("TABLE_NAME = '" + tableName + "'");
if(rows.Length > 0)
{
// Now you are sure to have a valid table in your textbox
// and could use the input value without risking an Sql Injection
string sql = "INSERT INTO [" + tableName + "] ([itemserial]," +
"[itemname],[itemcount],[itemimage]) " +
"VALUES(#itemserial,#itemname,#itemcount,#itemimage)";
.... the remainder of your code that use the query above....
}
else
MessageBox.Show("Please enter a valid name for your table");
Extending this approach you could change your TextBox to a ComboBox with ComboBoxStyle set to DropDownList (to block typing) and fill the ComboBox with the names returned by the GetSchema call above....
tablename = textbox1.text;
sql = string.Format("INSERT INTO {0} ([itemserial],[itemname],[itemcount],[itemimage])VALUES(#itemserial,#itemname,#itemcount,#itemimage)", tablename);
Although I would strongly recommend against this as it allows people to enter whatever they want into that textbox. Something like:
Robert; DROP TABLE Students;--
Which is discussed in more detail here:
How does the SQL injection from the "Bobby Tables" XKCD comic work?
Change your query like this
sql = "INSERT INTO "+tablename+" ([itemserial],[itemname],[itemcount],[itemimage]) VALUES (#itemserial,#itemname,#itemcount,#itemimage)";
I have a SELECT COUNT(*) statement in C#/ASP.NET and I want to store the result as an int to use as an IF condition. However I am getting an error in visual studio:
Error:System.Data.SqlClient.SqlException (0x80131904): The data types text and varchar are incompatible in the equal to operator. at System.Data.SqlClient.SqlConnection.
It tells me its occurring at the int temp line. The columns I'm accessing in the database table are of text type.
conn.Open();
String checkEmail = "select count(*) from Players where PlayerEmail= '" + txtEmailLogIn.Text + "'";
SqlCommand com = new SqlCommand(checkEmail, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp > 0)
{
}
The problem is in your SQL. You can't use = when comparing TEXT data types, instead you can use LIKE:
String checkEmail = "select count(*) from Players where PlayerEmail LIKE '" + txtEmailLogIn.Text + "'";
Be warned though, that you are opening yourself up to SQL injection attacks when composing SQL strings like this.
DavidG's answer above works. However, if you have the opportunity to change the database schema, you could also fix the error by changing the PlayerEmail column from text to varchar(max). The text data type has been deprecated since at least 2005.
Before you comment please note that I understand that my code is vulnerable to SQL injection, please disregard any comments about it being vulnerable for purposes of simplicity
I've checked around the website for answers but none seem to fit my situation, many are PHP.
I am trying to update information on a MySQL database from C# Forms Application on Visual Studio 2012, so I've allowed the user to input data but I want them to be able to update their data.
I've tried all sorts of different methods many give me errors, I feel like I'm very close with this method.
string Connection = "server = xxxx; " + "database = xxxxx; " + "uid = xxxx;"+ "pwd = xxxxx;";
MySqlConnection Conn = new MySqlConnection(Connection);
try
{
MySqlDataAdapter dAdapter = new MySqlDataAdapter("SELECT * FROM example", Conn);
DataTable dTable = new DataTable();
dAdapter.Fill(dTable);
DataRow dr = dTable.NewRow();
dr["TestData1"] = Convert.ToInt32(cboTestData1.Text);
dr["TestData2"] = txtTestData2.Text;
dr["TestData3"] = Convert.ToInt32(txtTestData3.Text);
dTable.Rows.Add(dr);
string Query = "Update example(field 1, field 2, field 3) VALUES ("TestData1", "TestData2", "TestData3")";
dTable.Rows.Add(Query);
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dAdapter);
int iRowsAffected = dAdapter.Update(dTable);
if (iRowsAffected == 1)
{
MessageBox.Show("Record Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Error adding record", "Record Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
The issue is that it doesn't like the 'Query' code due to it being bad. It gives me this error message
Additional information: Input string was not in a correct
format.Couldn't store in ID Column. Expected
type is Int32.
I've looked around the internet for solutions but all either do not offer the same situation as mine or are related to PHP code.
The update query should be in a syntax of...
update SomeTable
set SomeField = NewValue,
AnotherField = AnotherValue
where
SomeKey = KeyIDTheUserWasWorkingWith
Also, for future, I know this is sample mach-up data/columns, but you should really use real table / column names. The sample data, we know could be made up to prevent confidentiality, but real structures are more practical to get answers accurate.
The INSERT statement is closer to what you have and is ...
insert into SomeTable
( fld1, fld2, fld3 )
values
( someFld1, anotherFld2, lastField )
Finally, with your column names, if you DO (but I never do), have columns with embedded spaces, be sure to
`wrap in tic marks`
, so the engine recognizes the whole string as the column name.
I think there is some confusion in your code.
The SELECT statement may be bringing back 4 fields such as: ID, TestData1, TestData2, TestData3.
You then fill a DataTable with the records retrieved from the database.
Next, you create a new DataRow in the DataTable (that will have the four columns that match the SELECT statement). You place values into the editable fields (not the ID field).
Then you add the DataRow to the DataTable.
Here its where it gets mixed up...
You create a SQL Update Query String - then add that string as a DataRow to the DataTable.
When updating the DataTable via the MySqlDataAdapter, the last DataRow is not a valid record to be parsed by the Adapter.
Try removing the two lines:
string Query = "Update example(field 1, field 2, field 3) VALUES ("TestData1", "TestData2", "TestData3")";
dTable.Rows.Add(Query);