add data in mysqldatabase using C# - mysql

Is my first time to using mysql as the backend for my ASP.NET application.
Am trying to Insert data into the table, but I keep having this error.
I have install the mysql connector. Can some one tell me where am doing wrong.
here is the error:
MySql.Data.MySqlClient.MySqlException was unhandled by user code
HResult=-2147467259
Message=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 '' at line 1
Source=MySql.Data
ErrorCode=-2147467259
Number=1064
StackTrace:
at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
at Agohealth.Requestlab.btnsubmit_Click(Object sender, EventArgs e) in C:\Users\PC3\Documents\Visual Studio 2010\Projects\Agohealth\Agohealth\LabRequest.aspx.cs:line 38
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
namespace hiredad
{
public partial class Requestlab : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
string connectionstring = ConfigurationManager.ConnectionStrings["LocalMySqlServer"].ConnectionString;
using (MySqlConnection conn = new MySqlConnection(connectionstring))
{
MySqlCommand cmd = new MySqlCommand();
conn.CreateCommand();
cmd.Connection = conn;
conn.Open();
cmd.CommandText=("INSERT INTO labrequest (Examination,TestName,RequestCode,PatientNumber,Date,Doctor)"
+ ("VALUES (?Examination,?TestName,?RequestCode,?PatientNumber,?Date,?Doctor"));
cmd.Parameters.Add("?Examination", MySqlDbType.VarChar).Value = DropDownList1.SelectedValue;
cmd.Parameters.Add("?TestName", MySqlDbType.VarChar).Value = dlistlabtestname.SelectedValue;
cmd.Parameters.Add("?RequestCode", MySqlDbType.VarChar).Value = txtrequestcode.Text;
cmd.Parameters.Add("?PatientNumber", MySqlDbType.VarChar).Value = txtreginum.Text;
cmd.Parameters.Add("?Date", MySqlDbType.Date).Value = labdate.Text;
cmd.Parameters.Add("?Doctor", MySqlDbType.VarChar).Value = txtdoctor.Text;
cmd.ExecuteNonQuery();
Message.Text = "Sucessfully inserted!";
}
}
}

Related

Could not create connection to Mysql database server in Android studio

Mysql version 8.0.15
Tried Mysql java Connector version 8.0.15;
8.0.29; 5.1.46. Those three version is not working
W/System.err: java.sql.SQLNonTransientConnectionException: Could not create connection to database server.
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:110)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1008)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825)
at com.mysql.cj.jdbc.ConnectionImpl.(ConnectionImpl.java:455)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199)
at java.sql.DriverManager.getConnection(DriverManager.java:580)
at java.sql.DriverManager.getConnection(DriverManager.java:218)
private static String diver = "com.mysql.cj.jdbc.Driver";
private static String url = "jdbc:mysql://10.0.2.2:3306/?";
//private static String url = "jdbc:mysql://localhost:3306/sql_store";
private static String user = "root";
private static String password = "123456";
public static Connection getConn(){
Connection conn = null;
try {
Class.forName(diver);
conn = (Connection) DriverManager.getConnection(url,user,password);
Log.e("connection", "success");
} catch (ClassNotFoundException e) {
Log.e("connection", "can not find class!");
e.printStackTrace();
} catch (SQLException e) {
Log.e("connection", "unsuccessful"+e.getSQLState());
e.printStackTrace();
}
return conn;
}

Update issue MS Access/C#

I have tried updateing the MS Database via c#. Although I haven't received any error, It doesn't update the database
private void Button1_Click(object sender, EventArgs e)
{
conn.Open();
string UpdateQuery = "Update NDS Set IATACode=#p2,City=#p3,Country=#p4 where ID=#p1";
OleDbCommand Update1 = new OleDbCommand(UpdateQuery, conn);
Update1.Parameters.AddWithValue("#p1", txtId.Text);
Update1.Parameters.AddWithValue("#p2", txtIata.Text);
Update1.Parameters.AddWithValue("#p3", txtCity.Text);
Update1.Parameters.AddWithValue("#p4", txtCountry.Text);
Update1.ExecuteNonQuery();
conn.Close();
ClearData();
ShowData();
MessageBox.Show("Updated");
}
OLEDB doesn't support named parameters. You need to supply parameters in order:
private void Button1_Click(object sender, EventArgs e)
{
conn.Open();
string UpdateQuery = "Update NDS Set IATACode=#p2,City=#p3,Country=#p4 where ID=#p1";
OleDbCommand Update1 = new OleDbCommand(UpdateQuery, conn);
Update1.Parameters.AddWithValue("#p2", txtIata.Text);
Update1.Parameters.AddWithValue("#p3", txtCity.Text);
Update1.Parameters.AddWithValue("#p4", txtCountry.Text);
Update1.Parameters.AddWithValue("#p1", txtId.Text);
Update1.ExecuteNonQuery();
conn.Close();
ClearData();
ShowData();
MessageBox.Show("Updated");
}

password salting asp.net default page error

I was trying to salt password in asp.net web application mysql but its shows this error.While running getting the error.Please anyone tell me the error?
Error:
Server Error in '/' Application.
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Could not load type 'DemoPage.Default'.
Source Error:
Line 1: <%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoPage.Default" %>
Line 2:
Line 3: <!DOCTYPE html>
Source File: /Default.aspx Line: 1
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3163.0
Code default.aspx:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebPage1
{
public partial class _default : System.Web.UI.Page
{
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader reader;
String queryStr;
String name;
protected void Page_Load(object sender, EventArgs e)
{
DoSQLQuery();
}
protected void submit_click(object sender, EventArgs e)
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
String queryStr = "";
cmd = new MySql.Data.MySqlClient.MySqlCommand("SELECT * FROM webapp.userregistration WHERE username = #name and password=#pas", conn);
cmd.Parameters.AddWithValue("#name", usernameTextBox.Text);
cmd.Parameters.AddWithValue("#pas", passwordTextBox.Text);
reader = cmd.ExecuteReader();
name = "";
while (reader.HasRows && reader.Read())
{
{
name = reader.GetString(reader.GetOrdinal("username")) + " " + reader.GetString(reader.GetOrdinal("password"));
}
//if the data matches the rows (username, password), then you enter to the page
if (reader.HasRows)
{
Session["uname"] = name;
Response.BufferOutput = true;
Response.Redirect("login.aspx", false);
}
else
{
passwordTextBox.Text = "invalid user";
}
}
reader.Close();
conn.Close();
}
private void DoSQLQuery()
{
try
{
}
catch (Exception e)
{
passwordTextBox.Text = e.ToString();
}
}
}
}

ExcelLibrary throwing Unauthorized Access Exception when attempting to create

As the title describes, my program is throwing an UnauthorizedAccessException when attempting to create an Excel file with the ExcelLibrary Library, which is strange given my computer hasn't got any restrictions regarding that. My code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Linq;
using System.Data;
using System.Data.OleDb;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ExcelLibrary;
namespace ExcelTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
string cs = "Provider=Microsoft.jet.OLEDB.4.0;Data Source=test1.mdb;";
ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
string[] x = new string[20];
for (int i = 1; i < x.Length; i++)
{
x[i] = "a";
}
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
OleDbConnection con = new OleDbConnection(cs);
con.Open();
string sql = "SELECT * FROM personas;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();
adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();
ds.Tables.Add(dt);
}
private void button1_Click(object sender, EventArgs e)
{
ExcelLibrary.DataSetHelper.CreateWorkbook("C:\\Users\\spereyra\\Documents\\Visual Studio 2012\\Projects\\deleteme\\ExcelTest", ds);
MessageBox.Show("creating excel");
}
}
}
Any ideas of what could the problem be? Thanks
EDIT: My exception log (it's in spanish, hope you don't mind):
System.UnauthorizedAccessException: Acceso denegado a la ruta de acceso 'C:\Users\spereyra\Documents\Visual Studio 2012\Projects\deleteme\ExcelTest'.
en System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
en System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
en System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
en System.IO.File.Open(String path, FileMode mode, FileAccess access, FileShare share)
en ExcelLibrary.CompoundDocumentFormat.CompoundDocument.Create(String file)
en ExcelLibrary.SpreadSheet.Workbook.Save(String file)
en ExcelLibrary.DataSetHelper.CreateWorkbook(String filePath, DataSet dataset)
en ExcelTest.Form1.button1_Click(Object sender, EventArgs e) en c:\Users\spereyra\Documents\Visual Studio 2012\Projects\deleteme\ExcelTest\Form1.cs:lĂ­nea 51
Found my error, I had specified the route to the file but forgot to type the filename and extension:
Instead of
ExcelLibrary.DataSetHelper.CreateWorkbook("C:\\Users\\spereyra\\Documents\\Visual Studio 2012\\Projects\\deleteme\\ExcelTest", ds);
MessageBox.Show("creating excel");
I should have put
ExcelLibrary.DataSetHelper.CreateWorkbook("C:\\Users\\spereyra\\Documents\\Visual Studio 2012\\Projects\\deleteme\\ExcelTest\\myExcel.xls", ds);
MessageBox.Show("creating excel");

Unable to catch MySqlException [Entity Framework WebAPI]

Code looks like this
public HttpResponseMessage PostUser(User user)
{
if (ModelState.IsValid)
{
try
{
db.Users.Add(user);
db.SaveChanges();
}
catch (MySqlException e)
{
....
}
}
}
WebServer return 500 Intenal due to duplicate Key, but never entered catch block.
I want to know how to catch MySqlException at above code.
ExceptionMessage: "Duplicate entry 'TEST2' for key 'IX_User'"
ExceptionType: "MySql.Data.MySqlClient.MySqlException"
StackTrace:
MySql.Data.MySqlClient.MySqlStream.ReadPacket()
MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
MySql.Data.MySqlClient.MySqlDataReader.NextResult()
MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
MySql.Data.Entity.EFMySqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed)
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()"
You can handle it by SQLException like this:
// your class code
try{
// do your work
}catch(SQLExcepetipn e){
// handle it
}
There is no MYSQL Exception class.