this is the code for lab 8 using System; using System.Data; using System.Data.Sq
ID: 3739987 • Letter: T
Question
this is the code for lab 8
using System;
using System.Data;
using System.Data.SqlClient;
namespace TestConsole
{
public class Student
{
public Student()
{
SID = 0;
FirstName = string.Empty;
LastName = string.Empty;
Address = string.Empty;
State = string.Empty;
City = string.Empty;
ZipCode = string.Empty;
Height = string.Empty;
}
public Student(int sId, string firstName, string lastName, string address,
string state, string city, string zipCode,string email, string height)
{
SID = sId;
FirstName = firstName;
LastName = lastName;
Address = address;
State = state;
City = city;
ZipCode = zipCode;
Email = email;
Height = height;
}
public int SID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string State { get; set; }
public string City { get; set; }
public string ZipCode { get; set; }
public string Email { get; set; }
public string Height { get; set; }
public void SetZipCode(string zipCode)
{
ZipCode = zipCode;
}
public void Display()
{
Console.WriteLine("SID: " + SID + "First Name: " + FirstName + "Last Name: " + LastName + "Address: " + Address + "State: " +
State + "City: " + City + "Zip Code: " + ZipCode + "Email: " + Email + "Height: " + Height);
}
public void SelectDB(int SID)
{
// Provide the query string with a parameter placeholder.
string queryString =
"SELECT SID, FirstName, LastName, Address, State, City, ZipCode, Email, Height from dbo.Students WHERE SID = @SID";
// Specify the parameter value.
int paramValue = SID;
// Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (SqlConnection connection =
new SqlConnection("Data Source=HOME-PC\SQLSERVER;Initial Catalog=College;Integrated Security=SSPI;"))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("@SID", paramValue);
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
SID = Convert.ToInt16(reader[0]);
FirstName = Convert.ToString(reader[1]);
LastName = Convert.ToString(reader[2]);
Address = Convert.ToString(reader[3]);
State = Convert.ToString(reader[4]);
City = Convert.ToString(reader[5]);
ZipCode = Convert.ToString(reader[6]);
Email = Convert.ToString(reader[7]);
Height = Convert.ToString(reader[8]);
}
reader.Close();
}
catch (Exception ex)
{
//"Data Source=HOME-PC\SQLSERVER;Initial Catalog=DataBaseName;User id=sa;Password=123;"
Console.WriteLine(ex.Message);
}
}
}
public void InsertDB(int sId, string firstName, string lastName, string address,
string state, string city, string zipCode, string email, string height)
{
SID = sId;
FirstName = firstName;
LastName = lastName;
Address = address;
State = state;
City = city;
ZipCode = zipCode;
Email = email;
Height = height;
SqlConnection conn = new SqlConnection();
// define INSERT query with parameters
string query = "INSERT INTO dbo.Students (SID, FirstName, LastName, Address, State, City, ZipCode, Email, Height) " +
"VALUES (@SID, @FirstName, @Lastname, @Address, @State, @City, @ZipCode, @Email, @Height) ";
// create connection and command
using (SqlConnection cn = new SqlConnection("Data Source=HOME-PC SQLSERVER;Initial Catalog=College;Integrated Security=SSPI;"))
using (SqlCommand cmd = new SqlCommand(query, cn))
{
// define parameters and their values
cmd.Parameters.Add("@SID", SqlDbType.Int).Value = SID;
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = FirstName;
cmd.Parameters.Add("@Lastname", SqlDbType.VarChar, 50).Value = LastName;
cmd.Parameters.Add("@Address", SqlDbType.VarChar, 50).Value = Address;
cmd.Parameters.Add("@State", SqlDbType.VarChar, 50).Value = State;
cmd.Parameters.Add("@City", SqlDbType.VarChar, 50).Value = City;
cmd.Parameters.Add("@ZipCode", SqlDbType.VarChar, 50).Value = ZipCode;
cmd.Parameters.Add("@Email", SqlDbType.VarChar, 50).Value = Email;
cmd.Parameters.Add("@Height", SqlDbType.VarChar, 50).Value = Height;
// open connection, execute INSERT, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
public void UpdateDB()
{
SqlConnection conn = new SqlConnection();
// define UPDATE query with parameters
string query = "Update dbo.Students SET FirstName = @FirstName, LastName = @Lastname, Address = @Address,"+
"State = @State, City = @City, ZipCode = @ZipCode, Email = @Email, Height = @Height WHERE SID = @SID";
// create connection and command
using (SqlConnection cn = new SqlConnection("Data Source=HOME-PC SQLSERVER;Initial Catalog=College;Integrated Security=SSPI;"))
using (SqlCommand cmd = new SqlCommand(query, cn))
{
// define parameters and their values
cmd.Parameters.Add("@SID", SqlDbType.Int).Value = SID;
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = FirstName;
cmd.Parameters.Add("@Lastname", SqlDbType.VarChar, 50).Value = LastName;
cmd.Parameters.Add("@Address", SqlDbType.VarChar, 50).Value = Address;
cmd.Parameters.Add("@State", SqlDbType.VarChar, 50).Value = State;
cmd.Parameters.Add("@City", SqlDbType.VarChar, 50).Value = City;
cmd.Parameters.Add("@ZipCode", SqlDbType.VarChar, 50).Value = ZipCode;
cmd.Parameters.Add("@Email", SqlDbType.VarChar, 50).Value = Email;
cmd.Parameters.Add("@Height", SqlDbType.VarChar, 50).Value = Height;
// open connection, execute UPDATE, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
public void DeleteDB()
{
SqlConnection conn = new SqlConnection();
// define DELETE query with parameters
string query = "DELETE dbo.Students WHERE SID = @SID";
// create connection and command
using (SqlConnection cn = new SqlConnection("Data Source=HOME-PC SQLSERVER;Initial Catalog=College;Integrated Security=SSPI;"))
using (SqlCommand cmd = new SqlCommand(query, cn))
{
// define parameters and their values
cmd.Parameters.Add("@SID", SqlDbType.Int).Value = SID;
// open connection, execute DELETE, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
}
//THIS IS THE MAIN METHOD
using System;
using System.Collections.Generic;
namespace TestConsole
{
class Program
{
// Execution starts here.
static void Main()
{
Student s1 = new Student(4, "Frank", "Jones", "123 Main", "Atlanta", "GA", "30133", "fj@yahoo.com", "3.2");
s1.Display();
Student s2 = new Student();
s2.SelectDB(2);
s2.Display();
Student s3 = new Student();
s3.InsertDB(33, "Frank", "Mayes", "123 Main street", "Atlanta", "GA", "30100", "fmayes@yahoo.com", "3.3f");
s3.Display();
Student s4 = new Student();
s4.SelectDB(2);
s4.DeleteDB();
Student s5 = new Student();
s5.SelectDB(1);
s5.SetZipCode("12345");
s5.UpdateDB();
}
}
}
But i am have troblues writing the code for lab 9 which quesion is as follows
Recall the Student class that you built in Lab #8(Student.java). You will be using this class to access the Database. Also recall the StudentGUI class that you built in Lab #1 or #2(StudentGUI.java).
You may want to create a Lab9 folder, and copy the above 2 files and all related files(the StudentGUI may have related Panel files, like BottomPanel.java) into the Lab10 folder.
Your task for this lab is to make a student’s data(name, email, gpa) show up in the StudentGUI.
The user will run the StudentGUI class, and the GUI will show up. The User will then enter a student ID number in the ID textfield and click the Find button. Your event code will read the ID number the user entered, use that ID number and the Student Business Object to retrieve that one student’s data from the DB(selectDB()). Lastly, pull out the individual data elements(i.e firstName) from the Student Business Object and put them into the appropriate textfields in the StudentGUI.
Also make the “Insert”, “Delete” and “Update” buttons work. Have fun.
Explanation / Answer
conn.ConnectionString =
"Data Source = 123.456.789.012" +
";Initial Catalog = DiscoverThePlanet" +
";User ID = TestUser" +
";Password = Test";
An even better solution is to use ConnectionStringBuilder.
System.Data.SqlClient.SqlConnectionStringBuilder builder =
new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "123.456.789.012";
builder["Initial Catalog"] = "DiscoverThePlanet";
builder["User ID"] = "TestUser";
builder["Password"] = "Test";
Console.WriteLine(builder.ConnectionString);
Or (as @Fischermaen mentioned) you can use the properties, instead of indexes. It's even more readable!
builder.DataSource = "123.456.789.012";
builder.InitialCatalog = "DiscoverThePlanet";
builder.UserID = "TestUser";
builder.Password = "Test";
Also, in this scenario you aren't using any user input, but beware of connection string injection when manually creating your connection string. ConnectionStringBuilder can help you avoid those.
A connection string injection attack can occur when dynamic string concatenation is used to build connection strings that are based on user input. If the string is not validated and malicious text or characters not escaped, an attacker can potentially access sensitive data or other resources on the server. For example, an attacker could mount an attack by supplying a semicolon and appending an additional value. The connection string is parsed by using a "last one wins" algorithm, and the hostile input is substituted for a legitimate value.
The connection string builder classes are designed to eliminate guesswork and protect against syntax errors and security vulnerabilities. They provide methods and properties corresponding to the known key/value pairs permitted by each data provider. Each class maintains a fixed collection of synonyms and can translate from a synonym to the corresponding well-known key name. Checks are performed for valid key/value pairs and an invalid pair throws an exception. In addition, injected values are handled in a safe manner.
A last (and, in my opinion, best) alternative is to move your connectionstring from code into a config. This will make it much easier for you to use the same code in different environments.
conn.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString];
And your config.
<connectionStrings>
<add name="MyConnectionString" connectionString="[ConnectionString goes here]" providerName="System.Data.SqlClient" />
</connectionStrings>
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.