I am trying to upload text file into mysql database using C# windows application (visual studio2019). But facing some issues while uploading file into database.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
using System.Diagnostics;
using System.IO;
namespace WindowsFormsApp5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
MySqlConnection connection;
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
//To where your opendialog box get starting location. My initial directory location is desktop.
openFileDialog1.InitialDirectory = "C://Desktop";
//Your opendialog box title name.
openFileDialog1.Title = "Select file to be upload.";
//which type file format you want to upload in database. just add them.
openFileDialog1.Filter = "Select Valid Document(*.txt;*.pdf; *.doc; *.xlsx; *.html)|*.txt;*.pdf; *.docx; *.xlsx; *.html";
//FilterIndex property represents the index of the filter currently selected in the file dialog box.
openFileDialog1.FilterIndex = 1;
try
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (openFileDialog1.CheckFileExists)
{
string path = System.IO.Path.GetFullPath(openFileDialog1.FileName);
label1.Text = path;
}
}
else
{
MessageBox.Show("Please Upload document.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
string filename = System.IO.Path.GetFileName(openFileDialog1.FileName);
if (filename == null)
{
MessageBox.Show("Please select a valid document.");
}
else
{
//we already define our connection globaly. We are just calling the object of connection.
MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;username=root;password=");
//MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT * FROM fileuploadwindows.fileupload", connection);
connection.Open();
MySqlCommand cmd = new MySqlCommand("insert into fileupload values('\\Document\\" + filename + "')", connection);
string path = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 10));
System.IO.File.Copy(openFileDialog1.FileName, path + "\\Document\\" + filename);
cmd.ExecuteNonQuery();
connection.Open();
MessageBox.Show("Document uploaded.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
I am not getting anything into database. Solve with the error please. Data is not coming into database. It is showing text file already exist or No database selected or column count doesnt match value count at row 1.
Help with the solution.
After saving into database i want to view its content from database in gridview.