473,657 Members | 2,598 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Create a table in *.mdb

16 New Member
Hi! Ok, I have existing *.mdb with nothing within. How can I create an empty table with a name "1A", for example? I heard about some connections... I don' t know.
Apr 5 '09 #1
6 5789
cloud255
427 Recognized Expert Contributor
Hi

You really need to be more specific here. This question spans 2 technologies, C# database connects and SQL.

I suggest you consult the MSDN for the code required to connect to a DB and one of the millions of sights regarding SQL code.

The C# section of your question is fairly easy to answer, please feel free to post any code which is causing you problems and we will have a look at it.

As for the SQL, this can be really simple or rather complex depending on what exactly you want to do with the table you create. I know a fair bit about SQL and could help you with some of the code but if you want indexes, primary keys and relations I really think you should post that section of your code in the Access Forum as its not in the scope of C#.

Again, read up on the code and feel free to post any code which is unclear to you and we'll have a look at it.

To give you a short explanation:
You need to create a database connection which uses a connection string containing the authentication information. Next you need to create an SQL command and finally execute this command against your database.

You will most probably also have to look at the security settings of your database to ensure that you can indeed execute the command.

Your next step will be to consider .config files which store the connection settings and possibly a separate namespace which will control data access and encapsulate DB responses.
Apr 5 '09 #2
ventsislav
16 New Member
OK. I have an empy *.mdb. Then in the code I have:

SqlConnection con = new SqlConnection;
SqlCommand cmd = con.CreateConne ction();

Then what I do with these? I mean if I want to create table called 1A in the mdb how these help me?
Apr 5 '09 #3
cloud255
427 Recognized Expert Contributor
Hi

Well, that connection of yours wont work. You need to specify a connection string. A connection string is a string variable which contains all the information needed to connect to a database, it will specify the database name, the server, username and the password needed to connect to the database.

Your SQL command needs 2 arguments, the SQL connection and a string which contains the SQL code to execute.

You then need to open the connection and execute the command:

Expand|Select|Wrap|Line Numbers
  1. SqlCommand.Connection.Open();
  2. SqlCommand.ExecuteNonQuery();
Let's start by seeing your connection string and command string, write those and put them in the code I have posted for you (remember to declare both the connection and the command using the New keyword.

Post that code and we'll take it further from there.
Apr 6 '09 #4
ventsislav
16 New Member
Ok, it 's like this. I have a form like that below, and assemble the following code.
So I understood it, but what I need to do, to make a table in the file created?



Expand|Select|Wrap|Line Numbers
  1. FileInfo MyFile;
  2. SqlConnectionStringBuilder ConStrBuilder = new SqlConnectionStringBuilder();
  3. static SqlConnection Con = new SqlConnection();
  4. SqlCommand Cmd;
  5. SqlDataReader DataReader;
  6.  
  7. ...
  8.  
  9. private void OK_Click(object sender, EventArgs e)
  10.     {
  11.         string ConStr = "SELECT * FROM MyData";
  12.  
  13.         object CheckName = FileNameCombo.SelectedItem;
  14.         object CheckTableNum = TableNumCombo.SelectedItem;
  15.         object CheckTableChar = TableCharCombo.SelectedItem;
  16.  
  17.         if ((null != CheckName) && (null != CheckTableNum) && (null != CheckTableChar))
  18.         {
  19.             MyFile = new FileInfo("Data\\" + FileNameCombo.SelectedItem.ToString() + ".mdb");
  20.  
  21.             for (int i = 0; i < 23; i++) // FileName selection
  22.                 for (int j = 0; j < 8; j++) // TableNum selection
  23.                     for (int k = 0; k < 9; k++) // TableChar selection
  24.                     {
  25.                         if (i == FileNameCombo.SelectedIndex)
  26.                         {
  27.                             MyFile.Create();
  28.  
  29.                             Close();
  30.                         } 
  31.                         else if (MyFile.Exists == true)
  32.                         {
  33.                             if(j == TableNumCombo.SelectedIndex)
  34.                                 if (k == TableCharCombo.SelectedIndex)
  35.                                 {
  36.                                     ConStrBuilder.UserID = "My_UserID";
  37.                                     ConStrBuilder.InitialCatalog = TableNumCombo.SelectedItem.ToString() +
  38.                                                                    TableCharCombo.SelectedItem.ToString();
  39.                                     ConStrBuilder.DataSource = "(local)";
  40.  
  41.                                     Con.ConnectionString = ConStrBuilder.ConnectionString;
  42.                                     Con.Open();
  43.  
  44.                                     Cmd = new SqlCommand(ConStr, Con);
  45.  
  46.                                     DataReader = Cmd.ExecuteReader(CommandBehavior.CloseConnection);
  47.  
  48.                                     DataReader.Close();
  49.                                 }
  50.  
  51.                             this.Close();
  52.  
  53.                             return;
  54.                         }
  55.                     }
  56.         }
  57.         else MessageBox.Show("Missig Data!", "Creating Table", 0, MessageBoxIcon.Exclamation);
  58.     }
  59.  
Apr 6 '09 #5
cloud255
427 Recognized Expert Contributor
Hi

I looked at your code and your almost there, below I have posted a neater version of connecting to a database and executing a command to create a table in the database:

Expand|Select|Wrap|Line Numbers
  1.  string tableName = "MyTable"; //fill this variable with the name of the table to be created
  2.             string colName = "ColName"; //Fill this variable with the column name
  3.             string dataType = "CHAR"; //Fill this variable with the datatype of the column
  4.  
  5.             //This is the string containing all the information required to connect to the database
  6.             string conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\mydatabase.mdb;User Id=admin;Password=;";
  7.  
  8.             //This is the command to execute against the database
  9.             string cmdString = "CREATE TABLE " + tableName + " (" + colName + " " + dataType + ")";
  10.  
  11.             OleDbConnection conn = new OleDbConnection(conString); //This is the connection to the database
  12.             OleDbCommand cmd = new OleDbCommand(cmdString, conn); //This is the SQL command which will execute using the connection
  13.  
  14.             try
  15.             {
  16.                 conn.Open(); //Open the connection to the database
  17.                 cmd.ExecuteNonQuery(); //Execute the command               
  18.             }
  19.             catch (Exception ex)
  20.             {
  21.                 MessageBox.Show(ex.Message); //Show any errors
  22.             }
  23.             finally
  24.             {
  25.                 conn.Close(); //Close the connection to the database
  26.             }
  27.  
I suggest you look into using loops for creating multiple columns by concatenating to the cmdString.

You could also create a struct array which stores the column name as well as the datatype and use this in your loops to make the code a bit neater.

I used a try catch block for the opening the connection to the database and executing the command, while using a finally section to close the connection. If the connection is already closed the conn.Close() will not do anything.

On a general note, instead of looping like you did above:

Expand|Select|Wrap|Line Numbers
  1. for (int i = 0; i < 23; i++) 
You created a control with a number of options and you loop through all the possible values supplied by this control, you can make the code more robust by going:

Expand|Select|Wrap|Line Numbers
  1. for (int i = 0; i < comboBox1.Items.Count; i++)
I hope this helps
Apr 9 '09 #6
ventsislav
16 New Member
No, no, the loops are only for constructing the name of the table from multiple choices in the comboboxes. I' ll get this combox1.Items.C ount. Thanks!
Apr 9 '09 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

4
4050
by: Phil Powell | last post by:
create table if not exists nnet_produkt_varegruppe ( nnet_produkt_varegruppe_id int not null auto_increment, primary key(nnet_produkt_varegruppe_id), nnet_produkt_varegruppe_navn varchar(255) not null ); create table if not exists nnet_produkt_farge ( nnet_produkt_farge_id int not null auto_increment, primary key(nnet_produkt_farge_id),
6
6572
by: dev | last post by:
how create a temp table as a copy of a existing table and then update1 field and insert the hole temp table back in the existing table? please any help? if i have 10 fields in 1 record and about 100 records and a field.status=1 in a existing_table and i want to create a temp_table with all the recordse and values of the existing_table and then update the field.status to 2 and insert in 1 query the temp_table in the existing_table
4
4434
by: Michael Jackson | last post by:
I have a stored procedure to create a table. In my program I want the user to name the table to be created, therefore I pass a parameter to the SP for the table name. I cannot get it to work. It creates a table called "@NewTableName". Any ideas? CREATE PROCEDURE dbo.sp_FFProduction_CreateTable (
7
9671
by: Wolfgang Kreuzer | last post by:
Hello all, I have two tables - Projects and ProjectStruct Table Projects contains master records of the projects, ProjectStruct allows to define a project herarchie and contains the fields PrjStructId, ProjectId, PrjStructName, ..., ParentId PrjStructParent contains a reference to the parent or to itselves if record is top-level-record for a project.
1
3349
by: poohnie08 | last post by:
i have a excel spreadsheet showing staff name, date,work hour, ot hour, slot1, slot2, slot3, slot4 and others). The "()" will keep repeating from day 1 until end of month. eg in excel spreadsheet, ============================================================================== A1 |A2 A3 A4 A5 A6 A7 A8 |A9 A10 A11 | 01/02/04 |02/02/04 StaffName |Work Hr OT Hr Slot1...
24
3099
by: flkeyman | last post by:
Work in legal office. Trying to create solid designed database structure. This is list of tables w/fields and primary keys. Any comments/advice greatly appreciated. tbl-Defendants CaseNumber (primary key) FirstName MiddleName LastName
6
7705
by: Peter Nurse | last post by:
For reasons that are not relevant (though I explain them below *), I want, for all my users whatever privelige level, an SP which creates and inserts into a temporary table and then another SP which reads and drops the same temporary table. My users are not able to create dbo tables (eg dbo.tblTest), but are permitted to create tables under their own user (eg MyUser.tblTest). I have found that I can achieve my aim by using code like...
27
3774
by: max | last post by:
Hello, I am a newbye, and I'm trying to write a simple application. I have five tables with three columns; all tables are identical; I need to change some data in the first table and let VB updates the same data in all other four tables in the right places. I know it would be possible by using the ForeignKeyConstraint object. I have created the tables using the DataSet Visual Tool and I know it doesn't create any ForeignKeyConstraint obj....
4
12427
by: etuncer | last post by:
Hello All, I have Access 2003, and am trying to build a database for my small company. I want to be able to create a word document based on the data entered through a form. the real question is this: can Access create the document and place it as an OLE object to the relevant table? Any help is greatly appreciated. Ricky
2
2430
by: lakuma | last post by:
Hi, I have a table called A (say) with columns called name, place, animal and thing. I would want to write an on insert trigger on this table, which would create a table with the name of the value entered in the name column. Let's say a new column is entered with the value of name column as mickey. I want to create a table called mickey, with the help of triggers. I'm really new to this and i would like some help. Thanks in advance for...
0
8425
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8326
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8845
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8622
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6177
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2745
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1973
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1736
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.