Syntax error (missing operator) in query expression 'System.Byte[]' - ms-access

Hi i was using stored procedure in SQL Server to pass parameters to the query ,
but now I'm changing my database to ms access and it's my first time to deal with.
how can i pass byte[] to sql query ?
bacause i got this error
Syntax error (missing operator) in query expression 'System.Byte[]'.
this is my code
public static int EditWhois(object ID,object Image, object Ranswer, object Fanswer1, object Fanswer2, object Fanswer3)
{
int result = 0;
String sql = "UPDATE Whois SET [Image]="+#Image+", Ranswer=" + Ranswer + ", Fanswer1=" + Fanswer1 + ",Fanswer2=" + Fanswer2 + ",Fanswer3=" + Fanswer3 + " WHERE ID=" + ID;
System.Windows.Forms.MessageBox.Show(sql);
cmd = new OleDbCommand(sql, con);
//cmd.Parameters.AddWithValue("#ID", ID);
//cmd.Parameters.AddWithValue("#Image", Image);
//cmd.Parameters.AddWithValue("#Ranswer", Ranswer);
//cmd.Parameters.AddWithValue("#Fanswer1", Fanswer1);
//cmd.Parameters.AddWithValue("#Fanswer2", Fanswer2);
//cmd.Parameters.AddWithValue("#Fanswer3", Fanswer3);
if (con.State != ConnectionState.Open)
{
con.Open();
result = cmd.ExecuteNonQuery();
con.Close();
}
return result;
}

Use # parameter substitution. Also as #BoltClock says, change you method signature.
public static int EditWhois(object ID,object Image, object Ranswer,
object Fanswer1, object Fanswer2, object Fanswer3)
{
int result = 0;
String sql = "UPDATE Whois SET [Image]=#Image, Ranswer=#Ranswer, " +
"Fanswer1=#Fanswer1, Fanswer2=#Fanswer2, Fanswer3=#Fanswer3 " +
"WHERE ID=#ID";
cmd = new OleDbCommand(sql, con);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#Image", Image);
cmd.Parameters.AddWithValue("#Ranswer", Ranswer);
cmd.Parameters.AddWithValue("#Fanswer1", Fanswer1);
cmd.Parameters.AddWithValue("#Fanswer2", Fanswer2);
cmd.Parameters.AddWithValue("#Fanswer3", Fanswer3);
if (con.State != ConnectionState.Open)
{
con.Open();
result = cmd.ExecuteNonQuery();
con.Close();
}
return result;
}

result is still 0;
i know the problem where it was .
if the connection is closed the query will be executed successfully , but if it is opend it will not be executed due to this condition .
if (con.State != ConnectionState.Open)
{
con.Open();
result = cmd.ExecuteNonQuery();
con.Close();
}
it must be
if (con.State != ConnectionState.Open)
{
con.Open();
}
result = cmd.ExecuteNonQuery();
con.Close();
thanks all .

Related

MySQL Process List has too many process. Is it normal?

I created an Android app like social media app. I'm using ASP.NET web services for fetching data with JSON or process data like INSERT, UPDATE, DELETE. And I'm using MySQL database.
Number of active users is about 2,5k and daily average is 1,5k.
Anyway, when I control process list with "show processlist;" on phpMyAdmin , there are a lot of process; some processes has Sleep command value. So this situation gets errors like decreasing app speed and some times "max_user_connections".
So, I closed all connections after completing process of database on Web Service, but still have that issue or errors.
[WebMethod]
public string ABC(int x, string y)
{
using (con = new MySqlConnection(conString))
{
List<Profile> result= new List<Profile>();
result.Add(new Profile
{
posts= ""
});
List<ClassA> resultA= new List<ClassA>();
query= "SELECT COUNT(FollowId) FROM Followings WHERE FUserId = " + x;
con.Open();
cmd = new MySqlCommand(query, con);
dr = cmd.ExecuteReader();
string count = "0";
while (dr.Read())
{
count = dr[0].ToString();
}
dr.Close();
con.Close();
query= "SELECT COUNT(FollowId) FROM Followings WHERE FollowingUserId = " + x;
con.Open();
cmd = new MySqlCommand(query, con);
dr = cmd.ExecuteReader();
string count2 = "0";
while (dr.Read())
{
count2 = dr[0].ToString();
}
dr.Close();
con.Close();
query= "SELECT .... FROM Posts WHERE UserId = " + x+ " ORDER BY PostId DESC LIMIT 30";
con.Open();
cmd = new MySqlCommand(query, con);
dr = cmd.ExecuteReader();
int i;
int count3 = 0;
while (dr.Read())
{
count3++;
i = 0;
resultA.Add(new ClassA
{
postId = Convert.ToInt32(dr[i]),
postUrl = dr[++i].ToString(),
... = Convert.ToInt32(dr[++i])
});
}
dr.Close();
con.Close();
string json = "";
if (resultA.Count > 0)
{
json = JsonConvert.SerializeObject(resultA);
}
result[0].posts = json;
json = "";
if (result.Count > 0)
{
json = JsonConvert.SerializeObject(result);
}
return json;
}
}
It's any example of my web methods. Where do I mistake ?
Thanks for replies.

signup data failed in asp.net using mysql database

i try to build signup code using asp.net and mysql
code is
protected void Button2_Click(object sender, EventArgs e)
{
try
{
string MyConnection2 = "Server=xxx; Port=3306 ; Uid=xxx; pwd=xxx;Database=maintainance";
string Query = "INSERT INTO `login`(`UName`, `UPasword`,`UserTypeID`,`Email`)VALUES('" + this.TextBox1.Text + "','" + this.TextBox2.Text + this.DropDownList1.SelectedValue +this.TextBox3.Text+ "');";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
Label3.Text = ("Your Data saved successfully");
while (MyReader2.Read())
{
}
MyConn2.Close();
}
catch
{
Label3.Text = ("Data saved failed");
}
}
but it shows me Data saved failed ... where is the error and how i correct this?
You have to pass value according to column before VALUES
string Query = "INSERT INTO `login`(`UName`, `UPasword`,`UserTypeID`,`Email`) VALUES ('" + this.TextBox1.Text + "','" + this.TextBox2.Text+"', '"+this.DropDownList1.SelectedValue+"' ,'"+this.TextBox3.Text+ "');";

Access import into SQL server not importing first line

I am using a function to import data from a access db into SQL server:
public string importDataFromAccess(string table, string fileName)
{
OleDbConnection OleDbConn = new OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", fileName));
try
{
string sSQLTable = table;
string myExcelDataQuery = "Select * from " + sSQLTable;
string sSqlConnectionString = connStr;
string sClearSQL = "DELETE FROM " + sSQLTable;
SqlConnection SqlConn = new SqlConnection(sSqlConnectionString);
SqlCommand SqlCmd = new SqlCommand(sClearSQL, SqlConn);
SqlConn.Open();
SqlCmd.ExecuteNonQuery();
SqlConn.Close();
OleDbCommand OleDbCmd = new OleDbCommand(myExcelDataQuery, OleDbConn);
OleDbConn.Open();
OleDbDataReader dr = OleDbCmd.ExecuteReader();
SqlBulkCopy bulkCopy = new SqlBulkCopy(sSqlConnectionString);
bulkCopy.DestinationTableName = sSQLTable;
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
}
OleDbConn.Close();
return "Done";
}
catch (Exception ex)
{
OleDbConn.Close();
return ex.ToString();
}
}
I noticed it isnt importing the first record of each table, can anyone help notice why and how to fix? Hopefully it is only the first row...
You shouldn't need the
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
}
And you just need to replace that with
bulkCopy.WriteToServer(dr);
The WriteToServer method
Copies all rows in the supplied IDataReader to a destination table
specified by the DestinationTableName property of the SqlBulkCopy
object.
But the dr.Read() that you have called has read the first line out of the Reader and advanced the IDataReader to the next record (so it is not accessible to the WriteServer method).

MySQL System.FormatException: Input string was not in a correct format

Currently, I am creating an application using ASP.NET MVC3 and MySQL and when I try to retrieve a user's first name from the databse I receive a System.FormatException: Input string was not in a correct format.
This is my code:
public string GetUserFirstName(UInt64 id)
{
DBConnections databaseCnnString = new DBConnections();
string connectionString = "server=123.123.com;user=me;database=db1;port=3306;password=abcdef";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
string sp_GetFName = "SP_GET_FNAME";
MySqlCommand cmd = new MySqlCommand(sp_GetFName, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters["id"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("first_name", MySqlDbType.VarChar);
cmd.Parameters["first_name"].Direction = ParameterDirection.Output;
object result = cmd.ExecuteScalar();
if (result != null)
{
string fname = Convert.ToString(result);
return fname;
}
else
{
string fname = "friend";
return fname;
}
}
catch (Exception ex)
{
throw (ex);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}
This is MySQL Stored Procedure:
CREATE DEFINER=`0001`#`%` PROCEDURE `SP_GET_FNAME`(IN id BIGINT(20), OUT first_name VARCHAR(60))
BEGIN
DECLARE user_id BIGINT(20) DEFAULT id;
DECLARE output VARCHAR(60);
SELECT `FName` FROM `users` WHERE USERID=user_id INTO output;
SET first_name = output;
END
The problem seems to be when executing cmd.ExecuteScalar().
What is my problem here?
Thank you in advance!
Copy and paste error on my part. The correct code that works as expected is:
public string GetUserFirstName(UInt64 id)
{
DBConnections databaseCnnString = new DBConnections();
string connectionString = "server=123.123.com;user=me;database=db1;port=3306;password=abcdef";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
string sp_GetFName = "SP_GET_FNAME";
MySqlCommand cmd = new MySqlCommand(sp_GetFName, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters["id"].Direction = ParameterDirection.Input;
cmd.Parameters.Add(new MySqlParameter("first_name", MySqlDbType.VarChar));
cmd.Parameters["first_name"].Direction = ParameterDirection.Output;
cmd.ExecuteScalar();
string fname = Convert.ToString((cmd.Parameters["first_name"].Value));
return fname;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}
CORRECTION: cmd.Parameters.Add(new MySqlParameter("first_name", MySqlDbType.VarChar));
NOT: cmd.Parameters.AddWithValue("first_name", MySqlDbType.VarChar);
In my case, the FNAME field in the user table cannot be NULL; therefore, checking for NULL values returned in the code is not necessary.
I would guess that the user is not found or the fname is null.
And I really hope you're not querying the database for each user column.
Good luck.
An additional comment.
When trying to return a string value the AddWithValue appears to be trying to convert the output from a string into a number. This results in the string format exception.

PgSQL Exception: column name not found

I am using postgresql-8.3-603.jdbc4.jar with jdk 1.6 in my application to do the db operations. I am getting the below exceptions at sometimes and doing restart helps to avoid this exceptions temporarily.
org.postgresql.util.PSQLException: The column name sender_id was not found in this ResultSet.
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.findColumn(AbstractJdbc2ResultSet.java:2502)
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getString(AbstractJdbc2ResultSet.java:2345)
at org.apache.commons.dbcp.DelegatingResultSet.getString(DelegatingResultSet.java:225)
at org.apache.commons.dbcp.DelegatingResultSet.getString(DelegatingResultSet.java:225)
at com.netcore.bulkrequest.db.FeedDAO.setFeedDetails(FeedDAO.java:142)
at com.netcore.bulkrequest.feed.Feed.getInstance(Feed.java:37)
at com.netcore.bulkrequest.core.BulkRequestTask.(BulkRequestTask.java:86)
at com.netcore.bulkrequest.core.BulkRequestValidate.getBulkRequestTaskObject(BulkRequestValidate.java:104)
at com.netcore.bulkrequest.core.BulkRequestValidate.run(BulkRequestValidate.java:57)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
Here is the code snippet:
public class FeedDAO {
/**
* Database connection pool object
*/
private final DBContext dbc;
private final Feed feed;
public static final String SENDER_ID_ATTRIBUTE = "sender_id";
/**
* Constructor
*
* #param dbc
* #param feed
*/
public FeedDAO(DBContext dbc, Feed feed) {
this.dbc = dbc;
this.feed = feed;
}
public void setFeedDetails() throws SQLException {
String feedDetailsQuery = "SELECT a.priority, b.keyword, b.welcome " +
" FROM feed AS a, pub_feed_info AS b " +
" WHERE a.resource_id = b.resource_id AND b.resource_id = ?";
String senderIdQuery = "SELECT b.attribute_value AS " +
SENDER_ID_ATTRIBUTE + " FROM " +
"attribute_master AS a, feed_attributes AS b " +
"WHERE a.attribute_id = b.attribute " +
" AND a.attribute_name='" + SENDER_ID_ATTRIBUTE + "' " +
" AND feed_id = ?";
Connection con = null;
PreparedStatement fdStmt = null;
PreparedStatement siStmt = null;
try {
con = dbc.getConnection();
//Get the feed details
fdStmt = dbc.getPreparedStatement(con, feedDetailsQuery);
fdStmt.setInt(1, this.feed.getFeedId());
fdStmt.execute();
ResultSet fdResults = fdStmt.getResultSet();
while (fdResults.next()) {
String keyword = fdResults.getString("keyword");
String welcomeMsg = fdResults.getString("welcome");
int priority = fdResults.getInt("priority");
if(null != keyword) {
this.feed.setKeyword(keyword);
} else {
this.feed.setKeyword(String.valueOf(this.feed.getFeedId()));
}
this.feed.setWelcomeMsg(welcomeMsg);
this.feed.setPriority(priority);
}
//Get the sender id
siStmt = dbc.getPreparedStatement(con, senderIdQuery);
siStmt.setInt(1, this.feed.getFeedId());
if(siStmt.execute()) {
ResultSet siResults = siStmt.getResultSet();
while(siResults.next()) {
String senderId = siResults.getString(SENDER_ID_ATTRIBUTE);
this.feed.setSenderId(senderId);
}
} else {
this.feed.setSenderId(Feed.DEFAULT_SENDER_ID);
}
} catch (SQLException ex) {
throw ex;
} finally {
if (fdStmt != null) { fdStmt.close(); }
if (siStmt != null) { siStmt.close(); }
if (con != null) { con.close(); }
}
}
}
Can anyone please help me to find the permanent fix?
Thanks,
Mani
The key part of the error is "The column name sender_id was not found in this ResultSet" -- te very first row. So, how about showing us the query that's looking for a column that's just not there, and maybe the results of executing that query interactively in pgsql, the relevant parts of your schema, etc? Surely you can't expect us to help you debug without seeing anything more than the exception traceback, with zero clues about your code and DB!