SQL Parameter as table doesn't work [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to return a DataTable with this method but SqlParameter is not working properly.
private DataTable GetTable(string tableName)
{
const string queryString = "SELECT * FROM #TABLE";
SqlCommand sqlCommand = new SqlCommand(queryString, _sqlConnection);
SqlParameter sqlParameter = new SqlParameter("#TABLE", SqlDbType.Text)
{
Value = tableName
};
sqlCommand.Parameters.Add(sqlParameter);
_sqlConnection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
_sqlConnection.Close();
dataAdapter.Dispose();
dataGridViewTable.DataSource = dataTable;
dataGridViewTable.AutoResizeColumns();
return dataTable;
}
I am sure connection is successful. Another method is working. This one doesn't. It throws a SqlException.

You can't pass a table name as a parameter. Also, use using to easily close/dispose of disposable resources.
Try this...
private DataTable GetTable(string tableName)
{
string queryString = "SELECT * FROM [" + tableName + "]";
DataTable dataTable = new DataTable(tableName);
using (SqlCommand sqlCommand = new SqlCommand(queryString, _sqlConnection))
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand))
{
_sqlConnection.Open();
dataAdapter.Fill(dataTable);
_sqlConnection.Close();
}
dataGridViewTable.DataSource = dataTable;
dataGridViewTable.AutoResizeColumns();
return dataTable;
}
EDIT: Added square brackets around table name in query to handle names with spaces.

Related

Additional information: Incorrect syntax near 's' [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
Would you please tell me where is my mistake ?!?
I cannot find any incorrect syntax near any 's' !.
Here is my Code :
public static DataTable InsertConnect(ComboBox Site , ComboBox server , ComboBox Host , ComboBox Domain , Label Price)
{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = Server.Connection;
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "insert into tblPrice(Site,Server,Host,Domain,Price)
values('" + Site.Text + "','" + server.Text + "','" + Host.Text + "','" + Domain.Text + "','" + Price.Text + "')'";
SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText, cn);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
The reason because you don't using SqlParameter for passing values to the query.
If you have used parameters then you will not have such a problem as some extra ' character in your query.
Always use SqlParameters.
public static DataTable InsertConnect(ComboBox Site , ComboBox server , ComboBox Host , ComboBox Domain , Label Price)
{
using (var cn = new SqlConnection(Server.Connection))
{
cn.Open();
using (var cmd = new SqlCommand())
{
cmd.Connection = cn;
cmd.CommandText = "insert into tblPrice(Site,Server,Host,Domain,Price) values (#Site, #Server, #Host, #Domain, #Price)";
var parameters = new[]
{
new SqlParameter { ParameterName = "#Site", .SqlDbType = SqlDbType.VarChar, .Value = Site.text },
new SqlParameter { ParameterName = "#Server", .SqlDbType = SqlDbType.VarChar, .Value = server.text },
new SqlParameter { ParameterName = "#Host", .SqlDbType = SqlDbType.VarChar, .Value = Host.Text },
new SqlParameter { ParameterName = "#Domain", .SqlDbType = SqlDbType.VarChar, .Value = Domain.Text },
new SqlParameter { ParameterName = "#Price", .SqlDbType = SqlDbType.VarChar, .Value = Price.Text }
}
cmd.Parameters.AddRange(parameters);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
Then you can use constructor of SqlDataAdapter which takes SqlCommand as parameter, because your cmd contain all needed information for running query.
The problem is probably in one of the parameters which contains an apostrophe ('). Try to print out cmd.CommandText and you will see that it is not a valid SQL command.
On a related note, that is the foundation of SQL injection. Solution is not to construct SQL commands by concatenating values, especially strings. Instead, use command parameters and construct parameterized commands.
You can learn more on MSDN: How to: Execute a Parameterized Query

MySqlDataAdapter Fill input string format?

I'm getting an error when trying to fill a data table with data from a MySQL query using the adapter.
VisualStudio it's telling me the error, "Input String was not in a correct format," is on the line with adapter.Fill(myDataTable); (The procedure is just a basic select statement that returns some rows with text, varchar, and datetime values.)
the method is called like this: GetDataTable("CALL SomeProc()");
public static DataTable GetDataTable(string query)
{
string ConnString = ConfigurationManager.ConnectionStrings["randomconnstr"].ConnectionString.ToString();
MySqlConnection conn = new MySqlConnection(ConnString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand(query, conn);
DataTable myDataTable = new DataTable();
conn.Open();
try
{
adapter.Fill(myDataTable);
}
finally
{
conn.Close();
}
return myDataTable;
}
Your missing a quotation mark, it doesn't look like you have closed the string.
GetDataTable(#"CALL SomeProc()");
EDIT **
Try Adding this :-
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
Try changing this
GetDataTable("CALL SomeProc()");
To This :
GetDataTable("SomeProc");

how can i put # in select sql statement?

I have to use the "#"(I don't know it's name). I can use it in update delete or insert statements but I cannot use it in there it gives URL MUST BE DECLARED
//SQL string to count the amount of rows within the OSDE_Users table
string sql = "SELECT * FROM RSSFeeds where URL = #URL";
SqlCommand cmd = new SqlCommand(sql, Connect());
cmd.Parameters.Add("#URL", SqlDbType.VarChar, 500).Value = url;
closeConnection();
SqlDataAdapter adapt = new SqlDataAdapter(sql, Connect());
DataSet ds = new DataSet();
adapt.Fill(ds);
// result of query filled into datasource
adapt.Dispose();
closeConnection();
return ds;
I can only suppose that this line is not correct:
cmd.Parameters.Add("#URL", SqlDbType.Int).Value = url;
Probably URL is not an Int but a NVarChar or other character type
If this is the case then change your line in this way
(255 is the supposed length of your field URL)
cmd.Parameters.Add("#URL", SqlDbType.NVarChar, 255).Value = url;
And, by the way, '#' is called "Parameter Prefix"
EDIT: Seeing the last edit from the OP I update my answer to show what I think is the correct way to go.
//SQL string to count the amount of rows within the OSDE_Users table
string sql = "SELECT * FROM RSSFeeds where URL = #URL";
DataSet ds = new DataSet();
using(SqlConnection cnn = Connect())
using(SqlCommand cmd = new SqlCommand(sql, cnn))
{
cmd.Parameters.Add("#URL", SqlDbType.VarChar, 500).Value = url;
using(SqlDataAdapter adapt = new SqlDataAdapter(cmd))
{
adapt.Fill(ds);
}
}
return ds;
What I have changed:
Encapsulated every disposable object inside an using statement that
is guaranteed to close/dispose objects
Called Connect() just one time and captured the SqlConnection returned to
reuse without creating another one
Created the SqlDataAdapter using the SqlCommand created before (so
the #URL parameter reaches the Sql)
The OP used a closeConnection() and we don't see the internal of this method, but I think that using is enough to close and dispose the connection.
EDIT: The line that creates SqlDataAdapter should be
using(SqlDataAdapter adapt = new SqlDataAdapter(cmd))
cmd.Parameters.AddWithValue("#URL", url);
should work

SqlDataAdapter.Update: Are there SQL version requirements?

I know there are questions like this already, but I've combined all the common code to the answers and still am getting no success, so here I am.
Here's the deal. I have a block of code using SqlDataAdapter.Update to insert new rows into an existing table...
string command = "SELECT * FROM " + tableName;
// Initialize connection
if (oConn == null)
{
oConn = new SqlConnection(mainConnStr);
}
sCmd = new SqlCommand(command, oConn);
sCmd.CommandText = command;
SqlDataAdapter sDA = new SqlDataAdapter(sCmd);
DataSet ds = new DataSet();
oConn.Open();
sDA.Fill(ds, tableName);
oConn.Close();
DataTable dt = ds.Tables[tableName];
//Add each row.
for (int i = 0; i < queryResult.Rows.Count; i++)
{
dt.ImportRow(queryResult.Rows[i]);
}
// Handle the command building for the table update.
SqlCommandBuilder sCB = new SqlCommandBuilder(sDA);
oConn.Open();
sDA.Update(ds, tableName);
oConn.Close();
As mentioned, this works fine. However, if I try very similar code with a two-column test table (testInt, an int non-null; and testSTring, a varchar(50), null-allowed)...
private static void Main(string[] args)
{
SqlConnection = /* Build connection */
string sqlQuery = "SELECT * FROM TestTable WHERE 0 = 1";
SqlDataAdapter sDA = new SqlDataAdapter(sqlQuery, conn);
DataSet dataSet = new DataSet();
conn.Open();
sDA.Fill(dataSet);
conn.Close();
DataRow newRow = dataSet.Tables[0].NewRow();
newRow["testInt"] = 12;
SqlCommandBuilder cb = new SqlCommandBuilder(sDA);
conn.Open();
sDA.Update(dataSet);
conn.Close();
}
This code does nothing, and I can't figure out what in the world the difference is. (I should note that I've also tried using ImportRow instead of the NewRow technique.) Even when I try this block of code with the same tables as the first block (the working block), it still won't update the data.
Therefore, my question is: What fine details must be accounted for when using SqlDataAdapter.Update?
Thanks.
-F
You have to add the row to the DataSet
DataRow newRow = dataSet.Tables[0].NewRow(); // this doesn't add a new row to the data set
dataSet.Tables[0].Rows.Add(newRow); // you have to call this after

Bulk import from MS Access and Insert into Sql Server [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to read records from MS Access database and Insert into Sql server database, the process should be bulk insertion. I'm using asp.net/vb.net
First of all read data from Excel sheet
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("~/temp/") + "FileName.xlsx; Extended Properties=Excel 12.0;";
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand selectCommand = factory.CreateCommand();
selectCommand.CommandText = "SELECT ColumnNames FROM [Sheet1$]";
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
selectCommand.Connection = connection;
adapter.SelectCommand = selectCommand;
DataTable dtbl = new DataTable();
adapter.Fill(dtbl);
// Then use SQL Bulk query to insert those data
if (dtbl.Rows.Count > 0)
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destConnection))
{
bulkCopy.ColumnMappings.Add("ColumnName", "ColumnName");
bulkCopy.ColumnMappings.Add("ColumnName", "ColumnName");
bulkCopy.DestinationTableName = "DBTableName";
bulkCopy.WriteToServer(dtblNew);
}
}
private void Synchronize()
{
SqlConnection con = new SqlConnection("Database=DesktopNotifier;Server=192.168.1.100\\sql2008;User=common;Password=k25#ap;");
con.Open();
SqlDataAdapter adap = new SqlDataAdapter("SELECT * FROM CustomerData", con);
DataSet ds = new DataSet();
adap.Fill(ds, "CustomerData");
DataTable dt = new DataTable();
dt = ds.Tables["CustomerData"];
foreach (DataRow dr in dt.Rows)
{
string File = dr["CustomerFile"].ToString();
string desc = dr["Description"].ToString();
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;" + #"Data Source=D:\\DesktopNotifier\\DesktopNotifier.accdb";
OleDbConnection conn = new OleDbConnection(conString);
conn.Open();
string dbcommand = "insert into CustomerData (CustomerFile, Description) VALUES ('" + File + "', '" + desc + "')";
OleDbCommand mscmd = new OleDbCommand(dbcommand, conn);
mscmd.ExecuteNonQuery();
}
}
private void Configuration_Load(object sender, EventArgs e)
{
LoadGridData();
LoadSettings();
}
Just my two cents...
Using code like this:
DataSet ds = new DataSet();
adap.Fill(ds, "CustomerData");
You should be aware the the data adapter fill method is going to READ ALL data into memory. So if you have zillions of rows... think twice.

Categories