My
from 的MySQL
和It should work for SQL providing you use a connection string built for SQL server with your own credentials. This example code was pulled from a static class in a working MySQL project. For your sanity, I will remove the static modifiers and the classes, and assume you know how to structure the code yourself in a custom database class.public const string cString = "server=localhost;user id=root;password=root;persistsecurityinfo=True;database=visuals_db;port=8889";
public const string execSelectUnameQuery = "SELECT username from users WHERE [email protected]";
public const string execSelectIDQuery = "SELECT id from users WHERE [email protected]";
public const string execUpdateNameQuery = "UPDATE users SET [email protected] WHERE [email protected] AND [email protected];";
public const string execInsertUserQuery = "INSERT INTO users (name,username,email,password) VALUES (@Fname,@Uname,@Email,@Pass)";
public const string execDeleteUserQuery = "DELETE FROM users WHERE [email protected]";
public MySqlConnection Con = new MySqlConnection(cString);
//The insert method :: Each method takes one argument, this will be the statement declared above. Just pass in the variable name for the insert statement.
public bool Insert(string Statement)
{
try //Do not nest try catch blocks, except, declare more than one catch exception in one try block. Each catch can be added for the different exceptions that may arise.
{
if (Con != null)
//Check connection reachable and open it if its closed.
{
DoConnection(); //While the connection is closed, open it
using (MySqlCommand cmd = new MySqlCommand(Statement, Con)) //Build the command, and pass in the statement with the connection.
{ /* Use using blocks for they are self disposing when done using.
The below parameters takes the parameter name, and then the value of that parameter
So for the first parameter, we are setting the Name of the person for Fname parameter name */
cmd.Parameters.AddWithValue("@Fname", myAccount.Name); //Where myAccount would be the class holding your clients user details
cmd.Parameters.AddWithValue("@Uname", myAccount.Username);
cmd.Parameters.AddWithValue("@Email", myAccount.Email);
cmd.Parameters.AddWithValue("@Pass", myAccount.Password);
//Notice Fname, Uname, Email, Pass are the placeholders for the values and they are found in the executing statement above. This is how parameters should be used or you risk [URL='//en.wikipedia.org/wiki/SQL_injection']SQL Injection[/URL] attacks.
//Always use parameterized command queries!! And use add with value since add is deprecated
cmd.ExecuteNonQuery(); //Execute the query
}
DoConnection(); //Close the connection.
return true; //Tell the calling code success
}
return false; //Statement wont execute
}
catch (Exception ex)
{ //Then catch all errors you might miss
MessageBox.Show(string.Concat("Tell the developer there is an error at ", ex.StackTrace));
return false;
}
DoConnection()
method being called above opens and closes the connection based on its state. public bool DoConnection() //Open and close the connection with this method
{
//We devised a switch statement to open and close the connection depending on its current state
switch (Con.State == ConnectionState.Closed)
{
case true:
Con.Open();
return true;
case false:
Con.Close();
return false;
}
return false;
}
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 System.Data.OleDb;
using System.Data.Odbc;
namespace WFA61719
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new System.Data.SqlClient.SqlConnection("Server= xyz; Database = DatabaseName; Integrated Security = SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT count(*) FROM table";
string record = cmd.ExecuteScalar().ToString();
MessageBox.Show("Total records : " + record);
conn.Close();
}
}
}
Did you mean VB.NET?
.NET是一个基于各种语言的框架,例如C#,VB.NET,F#,IronPython等。
发布您在VB.NET中使用的连接字符串以及在C#中使用的连接字符串。
mC = New SqlConnection("Initial Catalog = dbName; Data Source = Server; Integrated Security = SSPI;")
Cmd = mC.CreateCommand
Cmd.CommandText = "SELECT * FROM table"
mC.Open()
myReader = Cmd.ExecuteReader()
SqlConnection sqlCon = new SqlConnection(@"Data Source = Server;Initial Catalog= dbName;Integrated Security = True;");
SqlDataAdapter sqlda = new SqlDataAdapter("SELECT * FROM table", sqlCon);
DataTable dtbl = New DataTable();
sqlda.Fill(dtbl);
Foreach(DataRow row in dtbl.Rows)
{
Console.WriteLine(row["col1"]);
}
Console.ReadKey();